簡體   English   中英

如何從多索引的兩個元素中減去一列?

[英]How can I subtract a columns from two elements of multi index?

我有一個具有多索引維度的面板數據框:國家和年份。 對於指數級別 = 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 中減去“United States”,可以使用xs

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

這里有一個例子:

arrays = [['United States', 'United States', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          [1, 2, 1, 2, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM