【发布时间】: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