【问题标题】:Accessing pandas groupby multiindex by second index通过第二个索引访问pandas groupby multiindex
【发布时间】:2019-01-07 17:20:40
【问题描述】:

找不到类似的问题。 假设我有 grouped_price 和 Multiindex (City, Month),看起来像这样:

City  Month     Price Sales 
LA   2017-01     10    10
     2017-02     15    20
     2017-05     20    35       
     2017-07     25    40
NY   2017-01     10     5
     2017-03     15    30
     2017-05     20    40       
     2017-06     25    45
CH   2017-01     7     10
     2017-02     11    22
     2017-07     30    41
OL   2017-01     9     10
     2017-02     17    10
     2017-05     20    30       
     2017-07     25    41 
     2017-08     30    47

所以对于“正常”循环顺序 City -> Month I did:

Cities = grouped_price.index.levels[0]
for city in Cities:
    labels = grouped_price.loc[city].index.labels
    levels = grouped_price.loc[city].index.levels
    Months = levels[0][labels[0]].unique() # for each City get a list of existing Months
    for mon in Months:
        # do things here
        x = grouped_price.loc[city, mon]  # ERROR here!

它有效。但是对于反向循环:

Months = grouped_price.index.levels[1]
Cities = grouped_price.index.levels[0]
for mon in Months:
    # Here I should get the list of Cities for specific Month
    for city in Cities:
        # do things here
        x = grouped_price.loc[city, mon]  # ERROR here!

给出错误,因为 MultiIndex 中并不存在所有的 city-mon 对。 我应该找到特定月份的城市列表,存在哪些配对,但我不明白如何。

Cities = grouped_price.loc[:, mon] - doesn't work

附:我知道我可以旋转表格,或者以相反的顺序对它们进行分组,但我不想这样做。

【问题讨论】:

    标签: python pandas indexing pandas-groupby multi-index


    【解决方案1】:

    一种解决方案是颠倒您的MultiIndex 级别的顺序:

    df = df.swaplevel(0, 1)
    

    或者,您可能还希望对新的MultiIndex 进行排序。这是一个最小的例子:

    df = pd.DataFrame([[0, 1, 2], [0, 2, 3], [1, 3, 4], [1, 1, 5]],
                      columns=['idx1', 'idx2', 'col'])
    
    df = df.set_index(['idx1', 'idx2'])
    df = df.swaplevel(0, 1).sort_index()
    
    print(df)
    
    idx2 idx1     
    1    0       2
         1       5
    2    0       3
    3    1       4
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 1970-01-01
      • 2018-12-09
      • 2021-03-27
      • 1970-01-01
      • 2012-10-02
      • 2020-06-05
      • 1970-01-01
      • 2018-02-03
      相关资源
      最近更新 更多