python - 如何将函数作为单独函数的一部分应用于 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 函数。
解决方案
该错误是由test_df
numpy 数组而不是 Pandas引起的DataFrame
。但即使使用真正的数据框,在方法中传递的函数apply
也会收到一个完整Series
的,默认情况下是一列,或者如果使用axis=1
.
你想要的(曾经test_df
是一个DataFrame)是:
test_df = test_df.apply(lambda x: x.apply(to_month_day))
推荐阅读
- python - 如何在不计算整个 DataFrame 的情况下从 Dask DataFrame 中提取前五个值?
- mysql - SQL查询以基于现有列的按功能分组的二进制列
- python - 焦点损失 U-net。TypeError:无法将 cuda:0 设备类型张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存
- php - 在 Laravel 关系对象上将字符串转换为整数
- windows - 如何使用新的 HLK 测试签署微型筛选器驱动程序
- python - 使用 Python Selenium 进行公司搜索
- python - Python:FileNotFoundError,来自 glob 输出,文件的完整路径是正确的
- python - 在唯一值上合并数据框
- python - 如何根据其他 2 列中的数据条件为列中的数据生成折线图
- ruby - Ruby:我有一个散列,其中键 = str.split(//) 和值 = 这些字符的索引。如果存在超过 1 个字符,我如何将多个索引添加到值