【问题标题】:How can I subtract a columns from two elements of multi index?如何从多索引的两个元素中减去一列?
【发布时间】:2020-12-05 10:36:24
【问题描述】:

我有一个具有多索引维度的面板数据框:国家和年份。对于指数级别 = 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

【问题讨论】:

  • [] 之后添加.loc 将无法完成分配...可以编辑您的问题以提供您的数据的minimal example 和您希望输出外观的表格喜欢吗?
  • 这可以表述为一个问题吗?
  • 谢谢你们的cmets,我试着更精确一点

标签: python pandas multi-index


【解决方案1】:

如果需要在整个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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多