如何从多索引的两个元素中减去一列?

问题描述

我有一个面板数据框,其中的尺寸具有多重索引:国家和年份。对于索引级别= 0的每个国家,我只想从美国除(或减去)一些变量。

使用伪代码

for country in countries_in_level0:
   Data[‘new_variable’][country] = Data[‘variable’][country] - Data[‘variable’][‘United States’] 

我想做的是

Data[‘new_variable’] = Data[‘variable’] - Data[‘variable’].loc[‘United States’,:]  

但是除了美国之外,每个国家/地区都可以使用NaN

解决方法

如果您需要在整个DataFrame中减去“美国”,则可以使用xs

Data - Data.xs(("United States"))

这里有个例子:

arrays = [['United States','United States','baz','foo','qux','qux'],[1,2,1,2]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples,names=['country','year'])
s = pd.DataFrame(10+(10*np.random.randn(8,2)),index=index)
s
                           0            1
country       year      
United States   1    8.012399    13.287124
                2   13.357553    -4.295128
baz             1   20.305391    12.381340
                2    0.070968     6.314961
foo             1   25.015921   -11.577952
                2    1.301654     6.000196
qux             1    4.198554    -6.915449
                2    5.071788    12.423901

s - s.xs(('United States'))
                             0          1
country       year      
United States   1     0.000000    0.000000
                2     0.000000    0.000000
baz             1    12.292992   -0.905785
                2   -13.286585   10.610089
foo             1    17.003522  -24.865077
                2   -12.055899   10.295324
qux             1   -3.813845   -20.202574
                2   -8.285765    16.719028

PS:如果只是美国重新分配问题,那就是

s.loc[['United States']]=1000