首页 > 解决方案 > 如何将函数作为单独函数的一部分应用于 DataFrame

问题描述

我正在尝试将正则表达式函数应用于 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 函数。

标签: pythonregexpandasfunctionnumpy-ndarray

解决方案


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

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

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

推荐阅读