[英]How can I apply a function to many columns in a dataframe using a single column as an argument?
I have a dataframe with 100+ columns I need to apply a function to, but I can't figure out how to pass the first column as an argument.我有一个包含 100 多列的数据框,我需要对其应用函数,但我不知道如何将第一列作为参数传递。
For example, if my table is:例如,如果我的表是:
df = pd.DataFrame({'argument':[1,2,0.5],
'day1':[4,5,6],
'day2':[5,1,2]})
argument day1 day2 day3...
0 1.0 4 5
1 2.0 5 1
2 0.5 6 2
And I have a function like this (mine is much more complicated, this is just for the example):我有一个这样的函数(我的要复杂得多,这只是为了举例):
def function (i,j):
return i * j
I would like my output to be:我希望我的输出是:
argument day1 day2 day3...
0 1.0 4 5
1 2.0 10 2
2 0.5 3 1
This is getting me very strange results, does anyone know what I'm doing wrong?这让我得到了非常奇怪的结果,有谁知道我做错了什么? Thank you!谢谢!
def function (i,j):
return i- j
df = df.apply(function, axis=1, j=df['argument'])
First, you have the wrong direction for your axis, it should be set to be 0 instead of 1.首先,您的轴方向错误,应将其设置为 0 而不是 1。
Second, if you apply your function like that, it will apply the function to your argument column.其次,如果您像这样应用您的函数,它将将该函数应用于您的参数列。 And it won't be the same as what you wanted there.它不会和你想要的一样。
So, change your code become like this所以,改变你的代码变成这样
import pandas as pd
def function (i,j):
return i * j
df = pd.DataFrame({'argument':[1,2,0.5],
'day1':[4,5,6],
'day2':[5,1,2]})
df2 = df.iloc[:,-2:].apply(function,axis=0,j=df['argument'])
df.iloc[:,-2:] = df2
print(df)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.