【问题标题】:Pandas multi-index unstack to single row熊猫多索引取消堆叠到单行
【发布时间】:2021-05-28 17:47:19
【问题描述】:

我很擅长简单的 Pandas,但在数据重塑和多索引方面遇到了困难。我有一个看起来像这样的多索引数据框(它不一定是多索引,但它似乎是正确的做法)

name index f1 f2 f3 calc1 calc2 calc3
fox 1 red white fur 0.21 1.67 -0.34
2 0.76 2.20 -1.02
3 0.01 1.12 -0.22
chicken 1 white yellow feathers 0.04 1.18 -2.01
2 0.18 0.73 -1.21
grain 1 yellow bag corn 0.89 1.65 -1.03
2 0.34 2.45 -0.45
3 0.87 1.11 -0.97

我想要的只是:

name f1 f2 f3 calc1_1 calc2_1 calc3_1 calc1_2 calc2_2 calc3_2 calc1_3 calc2_3 calc3_3
fox red white fur 0.21 1.67 -0.34 0.76 2.20 -1.02 0.01 1.12 -0.22
chicken white yellow feathers 0.04 1.18 -2.01 0.18 0.73 -1.21 NaN NaN NaN
grain yellow bag corn 0.89 1.65 -1.03 0.34 2.45 -0.45 0.87 1.11 -0.97

我认为这对于那里的熊猫大师来说一定很容易。谢谢大家的帮助!!

画了

【问题讨论】:

    标签: python pandas reshape multi-index


    【解决方案1】:

    尝试set_index + unstack 重塑为长格式

    new_df = df.set_index(['name', 'index', 'f1', 'f2', 'f3']).unstack('index')
    

    或通过pivot

    new_df = df.pivot(index=['name', 'f1', 'f2', 'f3'], columns='index')
    

    使用 sort_index 对 MultiIndex 进行排序:

    new_df = new_df.sort_index(axis=1, level=1)
    

    然后通过map + reset_index 减少MultiIndex:

    new_df.columns = new_df.columns.map(lambda s: '_'.join(map(str, s)))
    
    new_df = new_df.reset_index()
    

    new_df:

          name      f1      f2        f3  calc1_1  calc2_1  calc3_1  calc1_2  calc2_2  calc3_2  calc1_3  calc2_3  calc3_3
    0  chicken   white  yellow  feathers     0.04     1.18    -2.01     0.18     0.73    -1.21      NaN      NaN      NaN
    1      fox     red   white       fur     0.21     1.67    -0.34     0.76     2.20    -1.02     0.01     1.12    -0.22
    2    grain  yellow     bag      corn     0.89     1.65    -1.03     0.34     2.45    -0.45     0.87     1.11    -0.97
    

    完整代码:

    import pandas as pd
    
    df = pd.DataFrame({
        'name': ['fox', 'fox', 'fox', 'chicken', 'chicken', 'grain', 'grain',
                 'grain'],
        'index': [1, 2, 3, 1, 2, 1, 2, 3],
        'f1': ['red', 'red', 'red', 'white', 'white', 'yellow', 'yellow', 'yellow'],
        'f2': ['white', 'white', 'white', 'yellow', 'yellow', 'bag', 'bag', 'bag'],
        'f3': ['fur', 'fur', 'fur', 'feathers', 'feathers', 'corn', 'corn', 'corn'],
        'calc1': [0.21, 0.76, 0.01, 0.04, 0.18, 0.89, 0.34, 0.87],
        'calc2': [1.67, 2.2, 1.12, 1.18, 0.73, 1.65, 2.45, 1.11],
        'calc3': [-0.34, -1.02, -0.22, -2.01, -1.21, -1.03, -0.45, -0.97]
    })
    
    new_df = (
        df.set_index(['name', 'index', 'f1', 'f2', 'f3'])
            .unstack('index')
            .sort_index(axis=1, level=1)
    )
    
    new_df.columns = new_df.columns.map(lambda s: '_'.join(map(str, s)))
    
    new_df = new_df.reset_index()
    

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2016-09-06
      • 2020-02-18
      • 1970-01-01
      • 2020-01-02
      相关资源
      最近更新 更多