代码之家  ›  专栏  ›  技术社区  ›  ViSa

在Python中透视数据后,无法从数据帧中删除Multiindex

  •  0
  • ViSa  · 技术社区  · 3 年前

    我正在努力 pivot 双范畴变量的( status_type )在 python pandas 但它导致 multiindex 数据帧。我希望这是一个正常的数据帧,但不知道怎么做。如果有任何帮助,我将不胜感激。

    import pandas as pd
    import numpy as np
    
    # data
    test_df = pd.DataFrame({"id": np.arange(0, 8), 
                       "Window": np.random.rand(8), 
                       "status_type" : ["snap","perf","snap","perf","snap","perf","snap","perf"],
                       "status_level": [1, 2, 20, 35, 10, 5, 42, 9],
                      })
    
    test_df
    

    数据透视:

    test_df.pivot(index=['id','Window'],columns='status_type',values='status_level')
    

    结果为多索引df: result

    我已经尝试了以下代码将其重置为正常的数据帧并删除 状态_类型 专栏,但没用。

    (test_df
    .pivot(index=['id','Window'], columns='status_type', values='status_level')
    .reset_index()
    .drop('status_type', axis = 1)
    )
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   PaulS    3 年前

    可能的解决方案:

    (test_df.pivot(index=['id','Window'],columns='status_type',values='status_level')
     .rename_axis(None, axis=1).reset_index())
    

    输出:

       id    Window  perf  snap
    0   0  0.218674   NaN   1.0
    1   1  0.744127   2.0   NaN
    2   2  0.888882   NaN  20.0
    3   3  0.399161  35.0   NaN
    4   4  0.955325   NaN  10.0
    5   5  0.938839   5.0   NaN
    6   6  0.874510   NaN  42.0
    7   7  0.964414   9.0   NaN
    
        2
  •  1
  •   Pawan Sharma    3 年前

    This will help you resolve using reset and iloc ,and previous solution is more efficient as we are doing within the pivot function thanks to Paul

    这将帮助您解决使用重置和iloc的问题,而且由于Paul的帮助,以前的解决方案比我们在pivot函数中所做的更有效