pandas 熊猫从同一数据帧中减去 2 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26685600/
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 subtract 2 rows from same dataframe
提问by user308827
How do I subtract one row from another in the following dataframe (df):
如何在以下数据帧 (df) 中从另一行中减去一行:
RECL_LCC 1 2 3
RECL_LCC 35.107655 36.015210 28.877135
RECL_PI 36.961519 43.499506 19.538975
I want to do something like:
我想做类似的事情:
df['Difference'] = df['RECL_LCC']-df['RECL_PI']
but that gives:
但这给出了:
*** KeyError: 'RECL_LCC'
回答by unutbu
You can select rows by index value using df.loc:
您可以使用df.loc以下索引值选择行:
In [98]: df.loc['Diff'] = df.loc['RECL_LCC'] - df.loc['RECL_PI']
In [99]: df
Out[99]:
RECL_LCC 1 2 3
RECL_LCC 35.107655 36.015210 28.877135
RECL_PI 36.961519 43.499506 19.538975
Diff -1.853864 -7.484296 9.338160
回答by Vlad Bezden
you can use diff()function:
您可以使用diff()函数:
df.set_index('RECT_LCC', inplace=True)
df.diff(-1)
1 2 3
RECT_LCC
RECT_LCC -1.853864 -7.484296 9.33816
RECL_PI NaN NaN NaN
by default, it shifts by 1 row. In your case, since you subtracting next row instead of previous you need to set diff(-1)
默认情况下,它移动 1 行。在您的情况下,由于您减去下一行而不是前一行,因此您需要设置 diff(-1)

