我目前正在使用此数据框。按年份和国家/地区索引。我想做的就是减去2011年的“ military_exp”值和2010年的“ military_exp”值。有办法吗?
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
答案 0 :(得分:1)
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
更新
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