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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:37:21  来源:igfitidea点击:

Pandas subtract 2 rows from same dataframe

pythonpandassubtraction

提问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)