使用pandas apply函数的result_type参数

19
我想在我创建的pandas.DataFrame上使用apply,并为每一行返回一个值列表,其中每个值都是一个列。
我编写了以下代码:
import pandas as pd

def get_list(row):
  return [i for i in range(5)]

df = pd.DataFrame(0, index=np.arange(100), columns=['col'])


df.apply(lambda row: get_list(row), axis=1, result_type='expand')

当我添加 result_type='expand' 以将返回的数组更改为单独的列时,我会收到以下错误:
TypeError: ("<lambda>() got an unexpected keyword argument 'result_type'", 'occurred at index 0')

然而,如果我去掉result_type字段,代码就可以正常运行(返回一个数组列),可能是什么问题?
  • 我正在使用colab来运行我的代码

这段代码在 pandas 版本 0.23.3 中对我有效。 - Maarten Fabré
6
针对使用了最新版 pandas 出现此问题的人,请确保使用 df.apply() 而不是 df.groupby.apply(),因为 groupby apply 函数目前尚不支持 expand_result:https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.apply.html。 - charelf
当您在Series上运行apply时,您可能也会看到这种情况。来自1.4.2文档的说明:result_type...这些仅在axis=1(列)时起作用。https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html - Frank_Coumans
@Frank_Coumans Series.apply 没有 axis 或 result_type 参数;正确的链接是 https://pandas.pydata.org/docs/reference/api/pandas.Series.apply.html。 - fantabolous
1个回答

14

这段代码适用于pandas 0.23.3版本,你只需要在终端中运行pip install --upgrade pandas即可。

或者

你也可以不使用result_type来完成它:

def get_list(row):
    return pd.Series([i for i in range(5)])

df = pd.DataFrame(0, index=np.arange(100), columns=['col'])
pd.concat([df, df.apply(get_list, axis=1)], axis=1)

    col 0   1   2   3   4
0   0   0   1   2   3   4
1   0   0   1   2   3   4
2   0   0   1   2   3   4
3   0   0   1   2   3   4
4   0   0   1   2   3   4
...

顺便说一句,你不需要使用lambda,你可以这样做:

df.apply(get_list, axis=1, result_type='expand')

更新 result_type 在pandas 0.23的发布说明中已经公布: https://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0230,因此您需要更新。


2
如果操作者无法升级他们的模块怎么办? - asongtoruin
我尝试了你写的代码,它添加了一个包含数组的列,但没有将数组中的每个值添加到单独的列中。 - Ak-Mo
我将 get_list 函数的返回值更改为 pd.Series,你有检查过吗? - iDrwish
输出只有5行,我原本期望它能将5列添加到所有的100行。 - Ak-Mo
我只显示了五行...该函数应用于所有行。 - iDrwish
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接