你能告诉我如何使用像x['D'] :x['A']
这样的列范围,而不是将所有列作为参数在下面一一列出来运行吗?
df.loc[:,'F']=df.apply(lambda x: my_function(x['D'],x['C'],x['B'],x['A']), axis=1)
Were you looking for something like this?
df.loc[:,'F']=df.apply(lambda x: my_function(x.loc['D':'A']), axis=1)
If you need the parameters to be a list of columns and not a dataframe:
df.loc[:,'F']=df.apply(lambda x: my_function([x for x in x.loc['D':'A']]), axis=1)
You can try do something like this:
df.loc[:,'F']=df.apply(lambda x: my_function(*df.columns.difference(['F'])), axis=1)
if your columns are in order you can slice like this:
df.loc[:,'F']=df.apply(lambda x: my_function(*df.iloc[:,1:4])), axis=1)
Say you have a dataframe like this
E D C B A
______________________
0 8 9 9 6 1
1 8 4 1 4 3
2 0 4 6 9 3
And you want to apply some function func
to columns D
to A
, you can try
def func(x):
return sum(x[1:])
df.apply(func, axis=1)
output
0 25
1 12
2 22
dtype: int64
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.