简体   繁体   English

麻烦传入lambda来申请pandas DataFrame

[英]Trouble passing in lambda to apply for pandas DataFrame

I'm trying to apply a function to all rows of a pandas DataFrame (actually just one column in that DataFrame)我正在尝试将一个函数应用于 Pandas DataFrame 的所有行(实际上只是该 DataFrame 中的一列)

I'm sure this is a syntax error but I'm know sure what I'm doing wrong我确定这是一个语法错误,但我确定我做错了什么

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

The col column contains a bunch a datetime.datetime objects and and d1 is the earliest of them. col列包含一堆datetime.datetime对象,而d1是其中最早的。 I'm trying to get a column of the total number of seconds for each of the rows我正在尝试获取每一行的总秒数列

EDIT I keep getting the following error编辑我不断收到以下错误

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

I don't understand why axis is getting passed to my lambda function我不明白为什么axis被传递给我的lambda函数

EDIT 2编辑 2

I've also tried doing我也试过做

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

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

And I get the same error我得到了同样的错误

Note there is no axis param for a Series.apply call , as distinct to a DataFrame.apply call.注意有没有axis的PARAM Series.apply调用,如不同的DataFrame.apply电话。

Series.apply(func, convert_dtype=True, args=(), **kwds) 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

There is one for a df but it's unclear how you're expecting this to work when you're calling it on a series but you're expecting it to work on a row? df有一个,但不清楚当你在一个系列中调用它时你期望它如何工作,但你期望它连续工作?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM