【问题标题】:how to un-pivot multi-column data?如何取消透视多列数据?
【发布时间】:2020-10-16 22:00:11
【问题描述】:

我正在尝试 Unpivot 列并从 pandas 数据框中获取 1 个属性和 2 个值,有人可以帮助我吗?

原始数据:

 id Jan-Value1 Jan-Value2 Feb-Value1 Feb-Value2
 1  1          10         2          15
 2  0          5          3          20

希望输出:

 id Month Value1 Value2
 1  Jan   1      10
 1  Feb   2      15
 2  Jan   0      5
 2  Feb   3      20 

【问题讨论】:

    标签: python unpivot


    【解决方案1】:

    一种可能的方法是使用MultiIndexstack。对于这个解决方案,我假设 id 是数据框的索引:

    #df.set_index('id',inplace=True)  #set 'id' as index
    
    #creating a Multiindex using existing columns 
    df.columns = df.columns.str.split('-', expand=True).swaplevel(0,1)
    
    #stacking the dataframe
    df = df.stack().reset_index()
    
    #renaming the column 
    df.rename(columns={'level_1':'Month'},inplace=True)
    print(df)
    

    输出

       id Month  Value1  Value2
    0   1   Feb       2      15
    1   1   Jan       1      10
    2   2   Feb       3      20
    3   2   Jan       0       5
    

    【讨论】:

    • 添加了答案。请让我知道这对你有没有用。如果确实如此,请考虑接受/勾选答案
    【解决方案2】:

    你可以考虑 pandas.wide_to_long():

    import pandas as pd
    
    df = pd.DataFrame({
    "Jan-Value1": [1, 0],
    "Jan-Value2": [10, 5],
    "Feb-Value1": [2, 3],
    "Feb-Value2": [15,20]
    })
    
    df.columns = ["-".join(col.split("-")[::-1]) for col in df.columns]
    
    df["id"] = df.index
    
    transformed_df = pd.wide_to_long(df, ["Value1", "Value2"], i="id", j="Month", sep="-", suffix="\w+")
    

    由于 pandas 要求后缀以列的值结尾,因此我最终颠倒了列名的顺序(没有该转换,Value1 和 Value2 以月列结尾)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多