Python 在具有数值的列上的 Pandas 数据框上按行应用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29292114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apply function row wise on pandas data frame on columns with numerical values
提问by pdubois
I have the following data frame:
我有以下数据框:
import pandas as pd
df = pd.DataFrame({'AAA' : ['w','x','y','z'], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]})
Which looks like this:
看起来像这样:
In [32]: df
Out[32]:
AAA BBB CCC
0 w 10 100
1 x 20 50
2 y 30 -30
3 z 40 -50
What I want to do is to perform function operation on every row for every column except those with non-numerical value (in this case AAA
). In the real case the non-numerical case is always on first column, and the rest (could be greater than 2 columns) are always numerical.
我想要做的是对每一列的每一行执行函数操作,除了那些具有非数值的值(在这种情况下AAA
)。在实际情况下,非数字情况总是在第一列,其余(可能大于 2 列)总是数字。
The final desired output is:
最终所需的输出是:
AAA BBB CCC Score
0 w 10 100 110
1 x 20 50 70
2 y 30 -30 0
3 z 40 -50 -10
I tried this but failed:
我试过这个但失败了:
import numpy as np
df["Score"] = df.apply(np.sum, axis=1)
What's the right way to do it?
正确的做法是什么?
Update2:
更新2:
This is the code that give SettingWithCopyWarning
.
Please fresh start the ipython for testing.
这是给出的代码SettingWithCopyWarning
。请重新启动 ipython 进行测试。
import pandas as pd
import numpy as np
def cvscore(fclist):
sd = np.std(fclist)
mean = np.mean(fclist)
cv = sd/mean
return cv
def calc_cvscore_on_df(df):
df["CV"] = df.iloc[:,1:].apply(cvscore, axis=1)
return df
df3 = pd.DataFrame(np.random.randn(1000, 3), columns=['a', 'b', 'c'])
calc_cvscore_on_df(df3[["a","b"]])
采纳答案by unutbu
To select everything but the first column, you could use df.iloc[:, 1:]
:
要选择除第一列之外的所有内容,您可以使用df.iloc[:, 1:]
:
In [371]: df['Score'] = df.iloc[:, 1:].sum(axis=1)
In [372]: df
Out[372]:
AAA BBB CCC Score
0 w 10 100 110
1 x 20 50 70
2 y 30 -30 0
3 z 40 -50 -10
To apply an arbitrary function, func
, to each row:
要将任意函数func
, 应用于每一行:
df.iloc[:, 1:].apply(func, axis=1)
For example,
例如,
import numpy as np
import pandas as pd
def cvscore(fclist):
sd = np.std(fclist)
mean = np.mean(fclist)
cv = sd/mean
return cv
df = pd.DataFrame({'AAA' : ['w','x','y','z'], 'BBB' : [10,20,30,40],
'CCC' : [100,50,-30,-50]})
df['Score'] = df.iloc[:, 1:].apply(cvscore, axis=1)
print(df)
yields
产量
AAA BBB CCC Score
0 w 10 100 1.211386
1 x 20 50 0.868377
2 y 30 -30 NaN
3 z 40 -50 -5.809058