【问题标题】:Trouble passing in lambda to apply for pandas DataFrame无法传入 lambda 以申请 pandas DataFrame
【发布时间】:2015-05-23 04:48:09
【问题描述】:

我正在尝试将函数应用于 pandas DataFrame 的所有行(实际上只是该 DataFrame 中的一列)

我确定这是一个语法错误,但我知道我做错了什么

df['col'].apply(lambda x, y:(x - y).total_seconds(), args=[d1], axis=1)

col 列包含一堆 datetime.datetime 对象,d1 是其中最早的。我正在尝试获取每一行的总秒数列

EDIT我不断收到以下错误

TypeError: <lambda>() got an unexpected keyword argument 'axis'

我不明白为什么 axis 被传递给我的 lambda 函数

编辑 2

我也试过了

def diff_dates(d1, d2):
    return (d1-d2).total_seconds()

df['col'].apply(diff_dates, args=[d1], axis=1)

我得到同样的错误

【问题讨论】:

    标签: python pandas dataframe lambda apply


    【解决方案1】:

    注意Series.apply 调用没有axis 参数,这与DataFrame.apply 调用不同。

    Series.apply(func, convert_dtype=True, args=(), **kwds)

    func : function
    convert_dtype : boolean, default True
    Try to find better dtype for elementwise function results. If False, leave as dtype=object
    args : tuple
    Positional arguments to pass to function in addition to the value
    

    df 有一个,但是当你在一个系列中调用它时,不清楚你期望它如何工作,但你期望它连续工作?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      相关资源
      最近更新 更多