Search code examples
pandasdataframepandas-groupbysubtraction

Subtract rows in indexed dataframe


I am currently working with this data frame. It is indexed by year and Country. What I would like to do is to subtract the values for "military_exp" for year 2011 and the values for "military_exp" for year 2010. Is there a way of doing this?

                       gdp_share    military_exp
year    Country                     
2010    USA            5.0  768465792.0
        China          2.0  138028416.0 
        Korea          3.0  31117330.0  
        Russia         4.0  43120560.0  
2011    USA            5.0  758988352.0
        China          2.0  149022400.0
        Korea          3.0  31543720.0
        Russia         3.0  46022120.0

Solution

  • IIUC

    df.groupby(level=1)['military_exp'].diff()
    Out[195]: 
    year  Country
    2010  USA               NaN
          China             NaN
          Korea             NaN
          Russia            NaN
    2011  USA        -9477440.0
          China      10993984.0
          Korea        426390.0
          Russia      2901560.0
    Name: military_exp, dtype: float64
    

    Update

    df.loc[2011,'military_exp']-df.loc[2010,'military_exp']
    Out[197]: 
    Country
    USA       -9477440.0
    China     10993984.0
    Korea       426390.0
    Russia     2901560.0
    Name: military_exp, dtype: float64