pandas>=1.1.0中DataFrame.apply带raw=True返回多值触发ValueError咨询
问题根因
该问题是pandas 1.1.0版本后针对raw=True模式的返回值校验逻辑变更导致的:
raw=True时apply会向自定义函数传入numpy数组而非Series对象,返回多值时pandas会默认尝试将返回结果与原DataFrame的列索引对齐,你返回2个值但原DataFrame有3列,因此触发ValueError: Shape of passed values is (3, 2), indices imply (3, 3)报错- 0.23.4版本无该对齐校验逻辑,因此可以正常运行
可行解决方案
方案1:新增result_type='expand'参数(最便捷,无性能损失)
直接在调用apply时新增result_type参数即可,该参数会强制pandas将返回的多值展开为多列,不会破坏raw=True的性能优势:
# 新增result_type='expand'即可正常运行 df.apply(lambda row: custom_func_does_not_work(row), axis=1, raw=True, result_type='expand')
如果需要自定义列名,可直接给返回结果赋值columns:
res = df.apply(lambda row: custom_func_does_not_work(row), axis=1, raw=True, result_type='expand') res.columns = ['计算和', '计算积']
方案2:改用numpy原生的apply_along_axis(性能更优)
如果你的自定义函数本身就是基于numpy数组逻辑编写的,可以直接用numpy的遍历方法,性能略高于pandas的raw=True模式:
import numpy as np # 直接对df的底层numpy数组做遍历 res_arr = np.apply_along_axis(custom_func_does_not_work, axis=1, arr=df.values) # 转成DataFrame res = pd.DataFrame(res_arr, columns=['计算和', '计算积'])
内容的提问来源于stack exchange,提问作者godimedia
相关产品推荐
相关产品推荐

