【问题标题】:How can I pass arguments dynamically to a DataFrame.apply() lambda function?如何将参数动态传递给 DataFrame.apply() lambda 函数?
【发布时间】:2018-05-16 07:56:51
【问题描述】:

我正在尝试为 Dataframe 运行 Pandas apply() 方法以创建新列,如下所示:

df['new_column'] = df.groupby(groupby).apply(lambda x: some_function(x, df['existing_column']))

所以,基本上,我试图动态传递some_function 的第二个参数,相对于df['existing_column'] 存储为每一行的值(值不同)。

我得到的错误是常见的TypeError: 'Series' objects are mutable, thus they cannot be hashed。有没有合适的方法来解决这个问题?我尝试为每一行做一个 for 循环,但这会杀死我的 CPU。

【问题讨论】:

  • 你能解释更多吗?什么是参数?是否可以使用示例函数创建一些数据示例?

标签: python pandas apply


【解决方案1】:

如果每个组需要existing_column 的新列,我建议使用transform

df['new_column'] = df.groupby('col')['existing_column'].transform(lambda x: funct(x, par))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 2012-02-13
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    相关资源
    最近更新 更多