Pandas subtract 2 rows from same dataframe

user308827 picture user308827 · Nov 1, 2014 · Viewed 20.9k times · Source

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'

Answer

unutbu picture unutbu · Nov 1, 2014

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