【问题标题】:How to apply a function to a DataFrame as part of a separate function如何将函数作为单独函数的一部分应用于 DataFrame
【发布时间】:2020-07-08 12:58:22
【问题描述】:

我正在尝试将正则表达式函数应用于 DataFrame,它将日期格式的单元格替换为取自某些字符的字符串。

我在将函数应用于数据框本身时遇到问题。

这是我目前的代码:

def preprocess_test_data(self, test_df):

        def to_month_day(s):
            m = re.match("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", s)
            if m:
                return m[0][8:10].lstrip('0') + '-' + m[0][5:7].lstrip('0')
            return s

        test_df = test_df.apply(to_month_day)
        a = test_df[:,0].astype(str)
        b = test_df[:,1].astype(str)
        c = test_df[:,2].astype(str)
        d = test_df[:,3].astype(str)
        e = test_df[:,4].astype(str)
        f = test_df[:,5].astype(str)
        g = test_df[:,6].astype(str)
        h = test_df[:,7].astype(str)
        i = test_df[:,8].astype(str) 

我不断收到此错误:

AttributeError                            Traceback (most recent call last)

<ipython-input-10-a9f16326387d> in <module>
    183 
    184 # Dont change
--> 185 x_test_processed = my_model.preprocess_test_data(x_test)
    186 
    187 # Train your model

<ipython-input-10-a9f16326387d> in preprocess_test_data(self, test_df)
    119             return s
    120 
--> 121         test_df = test_df.apply(to_month_day)
    122         a = test_df[:,0].astype(str)
    123         b = test_df[:,1].astype(str)

AttributeError: 'numpy.ndarray' object has no attribute 'apply'

如何重新格式化数据框,以便它允许我运行 Re 函数。

【问题讨论】:

  • to_month_day(s) 方法需要传递一个参数;你错过了吗?请检查一次。
  • 不幸的是,如果我只是通过正常调用它来尝试这个,它就会给我:cannot use a string pattern on a bytes-like object
  • 你能在预处理函数中打印出test_df 的类型吗?似乎 test_df 是一个 numpy 数组。
  • 无论如何,DataFrame 上的 apply 将收到 Series 值。你到底想做什么?

标签: python regex pandas function numpy-ndarray


【解决方案1】:

该错误是由 test_df 是一个 numpy 数组而不是 Pandas DataFrame 引起的。但即使使用真正的数据框,apply 方法中传递的函数也会收到完整的Series,默认情况下是一列,如果使用axis=1,则默认为一行。

你想要的(曾经test_df 是一个DataFrame)是:

test_df = test_df.apply(lambda x: x.apply(to_month_day))

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2019-04-10
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多