python - 无法传入 lambda 以申请 pandas DataFrame

标签 python pandas dataframe lambda apply

我正在尝试将函数应用于 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)

我得到同样的错误

最佳答案

注意 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但不清楚当您在一个系列中调用它时您希望它如何工作,但您希望它连续工作?

关于python - 无法传入 lambda 以申请 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155310/

相关文章:

python - 表创建搞砸了

Python - 类上的描述符用于*设置*属性

python - Azure-blob-存储。使用 SAS token 访问容器

python - 将分隔符上的多列拆分为 Pandas 数据框中的行

python - Pandas - 列标题到行值

python - 如何在pandas数据框中按特定条件进行分组

python - 计算 Pandas 整个数据框中特定字符串的数量,并将其值添加到新列中

python - 如何使用 Paramiko 更改目录?

python - 用相似的索引替换 Pandas DataFrame 中的值

python - 计算 Pandas 系列中值的出现次数?