DataFrame.apply与str.extract一起抛出错误,即使函数在每个列序列上都有效



使用此示例DataFrame:df = pd.DataFrame([['A-3', 'B-4'], ['C-box', 'D1-go']])

调用单个列的提取作为系列工作正常:

df.iloc[:, 0].str.extract('-(.+)')
df.iloc[:, 1].str.extract('-(.+)')

也在另一个轴上:

df.iloc[0, :].str.extract('-(.+)')
df.iloc[1, :].str.extract('-(.+)')

所以,我希望使用apply会起作用(通过将摘录应用到每一列(:

df.apply(lambda s: s.str.extract('-(.+)'), axis=0)

但它抛出了一个错误:

Traceback (most recent call last):
File "C:ProgramDataMiniconda3envspy3libsite-packagesIPythoncoreinteractiveshell.py", line 3325, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-588-70b1808d5457>", line 2, in <module>
df.apply(lambda s: s.str.extract('-(.+)'))
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreframe.py", line 6487, in apply
return op.get_result()
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreapply.py", line 151, in get_result
return self.apply_standard()
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreapply.py", line 260, in apply_standard
return self.wrap_results()
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreapply.py", line 308, in wrap_results
return self.wrap_results_for_axis()
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreapply.py", line 340, in wrap_results_for_axis
result = self.obj._constructor(data=results)
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreframe.py", line 392, in __init__
mgr = init_dict(data, index, columns, dtype=dtype)
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreinternalsconstruction.py", line 212, in init_dict
return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreinternalsconstruction.py", line 51, in arrays_to_mgr
index = extract_index(arrays)
File "C:ProgramDataMiniconda3envspy3libsite-packagespandascoreinternalsconstruction.py", line 308, in extract_index
raise ValueError('If using all scalar values, you must pass'
ValueError: If using all scalar values, you must pass an index

使用axis=1会产生一个意外的结果,每一行都是一个系列:

Out[2]: 
0             0
0  3
1  4
1         0
0  box
1   go
dtype: object

我使用apply,因为我认为这将导致最快的执行时间,但对的其他建议持开放态度

您可以使用split。

df.apply(lambda s: s.str.split('-', expand=True)[1])
Out[1]: 
0   1
0    3   4
1  box  go

str.extract中展开的默认参数为True,它返回一个Dataframe。由于您将它应用于多个列,因此它会尝试返回多个数据帧。将expand设置为False以处理此问题,

df.apply(lambda x: x.str.extract('-(.*)', expand = False))
0   1
0   3   4
1   box go

相关内容

  • 没有找到相关文章

最新更新