pandas 列中的熊猫最大值并减去
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43327125/
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
Pandas max value in column and subtract
提问by magicsword
I have a pandas dataframe like:
我有一个Pandas数据框,如:
df = pd.DataFrame({'A':[1,1,1,2,2,2,3,3,3],
'B':[3,2,20,1,6,2,3,22,1]})
I would like to find the 'max' value in column 'B' then subtract this max value from all the values in column 'B' and create a new column 'C' with the new result. Max is 22 for bottom df.
我想在“B”列中找到“最大值”,然后从“B”列中的所有值中减去这个最大值,并使用新结果创建一个新列“C”。底部 df 的最大值为 22。
A B C
2 1 3 -19
1 1 2 -20
0 1 20 -2
3 2 1 -21
5 2 6 -16
4 2 2 -20
8 3 3 -19
7 3 22 0
6 3 1 -21
回答by EdChum
回答by jezrael
Use sub
for substracting max
value of column B
:
df['C'] = df['B'].sub(df['B'].max())
print (df)
A B C
0 1 3 -19
1 1 2 -20
2 1 20 -2
3 2 1 -21
4 2 6 -16
5 2 2 -20
6 3 3 -19
7 3 22 0
8 3 1 -21
Another solution with assign
:
另一个解决方案assign
:
df = df.assign(C=df['B'].sub(df['B'].max()))
print (df)
A B C
0 1 3 -19
1 1 2 -20
2 1 20 -2
3 2 1 -21
4 2 6 -16
5 2 2 -20
6 3 3 -19
7 3 22 0
8 3 1 -21