python - 即使函数适用于每个列系列,DataFrame.apply 与 str.extract 也会引发错误

标签 python python-3.x pandas dataframe

在此示例 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:\ProgramData\Miniconda3\envs\py3\lib\site-packages\IPython\core\interactiveshell.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:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\frame.py", line 6487, in apply
    return op.get_result()
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\apply.py", line 151, in get_result
    return self.apply_standard()
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\apply.py", line 260, in apply_standard
    return self.wrap_results()
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\apply.py", line 308, in wrap_results
    return self.wrap_results_for_axis()
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\apply.py", line 340, in wrap_results_for_axis
    result = self.obj._constructor(data=results)
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\frame.py", line 392, in __init__
    mgr = init_dict(data, index, columns, dtype=dtype)
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\internals\construction.py", line 212, in init_dict
    return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\internals\construction.py", line 51, in arrays_to_mgr
    index = extract_index(arrays)
  File "C:\ProgramData\Miniconda3\envs\py3\lib\site-packages\pandas\core\internals\construction.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

关于python - 即使函数适用于每个列系列,DataFrame.apply 与 str.extract 也会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58794687/

相关文章:

python - 连接python中多个大文件的每第n行

python - 在脚本结束时从 Python 3.5 切换到 2.7?

python - 从 pyodbc execute() 语句返回列名

python - 在迭代数据帧时将 pandas 数据帧中的特定行写入 csv 文件

python-3.x - pandas.ExcelWriter ValueError:xlsxwriter不支持追加模式

python - 值错误 : sampler option is mutually exclusive with shuffle pytorch

python - mypy 给出错误,类型不兼容 "Optional[int]";预期“Union[SupportsFloat、str、bytes、bytearray]

Python3 : read from a file and sort the values

python - 如何检测检测到的形状OpenCV的颜色

python - Discord.py message.author.id 返回回溯