问题描述
我正在尝试将一个函数应用于 Pandas DataFrame 的所有行(实际上只是该 DataFrame 中的一列)
I'm trying to apply a function to all rows of a pandas DataFrame (actually just one column in that 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)
col
列包含一堆 datetime.datetime
对象,d1
是其中最早的一个.我正在尝试获取每一行的总秒数列
The col
column contains a bunch a datetime.datetime
objects and and d1
is the earliest of them. I'm trying to get a column of the total number of seconds for each of the rows
编辑我不断收到以下错误
TypeError: <lambda>() got an unexpected keyword argument 'axis'
我不明白为什么 axis
会传递给我的 lambda
函数
I don't understand why axis
is getting passed to my lambda
function
编辑 2
我也试过
def diff_dates(d1, d2):
return (d1-d2).total_seconds()
df['col'].apply(diff_dates, args=[d1], axis=1)
我也遇到同样的错误
推荐答案
注意 调用,区别于 DataFrame.apply
打电话.
Note there is no axis
param for a Series.apply
call, as distinct to a DataFrame.apply
call.
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 但不清楚当你在一个系列中调用它时你期望它如何工作,但你期望它连续工作?
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?
这篇关于麻烦传入 lambda 以申请 Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!