Pandas subtract 2 rows from same dataframe

风流意气都作罢 提交于 2019-12-24 14:40:07

问题


How do I subtract one row from another in the following dataframe (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'

回答1:


You can select rows by index value using 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



回答2:


you can use diff() function:

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)



来源:https://stackoverflow.com/questions/26685600/pandas-subtract-2-rows-from-same-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!