【问题标题】:Python Pandas reorganize dataframePython Pandas 重组数据框
【发布时间】:2017-08-17 10:40:50
【问题描述】:

我有以下数据框:

Type  Label_1  Label_2  Label_3
A       1        5        3
B       3        2        1
C       2        1        2

我想将其格式化为如下所示:

Type  Label_type  Value
 A      Label_1    1
 A      Label_2    5
 A      Label_3    3
 B      Label_1    2
 B      Label_2    1

我怎样才能以最有效的方式做到这一点?我没有这样做...

【问题讨论】:

    标签: python python-2.7 pandas dataframe


    【解决方案1】:

    我们可以使用pd.melt方法:

    In [87]: pd.melt(df, 'Type')
    Out[87]:
      Type variable  value
    0    A  Label_1      1
    1    B  Label_1      3
    2    C  Label_1      2
    3    A  Label_2      5
    4    B  Label_2      2
    5    C  Label_2      1
    6    A  Label_3      3
    7    B  Label_3      1
    8    C  Label_3      2
    

    如果顺序很重要:

    In [89]: pd.melt(df, 'Type').sort_values(['Type', 'variable'])
    Out[89]:
      Type variable  value
    0    A  Label_1      1
    3    A  Label_2      5
    6    A  Label_3      3
    1    B  Label_1      3
    4    B  Label_2      2
    7    B  Label_3      1
    2    C  Label_1      2
    5    C  Label_2      1
    8    C  Label_3      2
    

    【讨论】:

    • 然后需要排序
    • 这是完美的,非常感谢!以前不知道这个:)
    • @Maple123,很高兴它有帮助:)
    • 对于任何想知道如何执行reverse程序的人:搜索pandas“pivot”函数
    【解决方案2】:

    使用stack:

    df=df.set_index('Type').stack().rename_axis(('Type','Label_type')).reset_index(name='Value')
    print (df)
      Type Label_type  Value
    0    A    Label_1      1
    1    A    Label_2      5
    2    A    Label_3      3
    3    B    Label_1      3
    4    B    Label_2      2
    5    B    Label_3      1
    6    C    Label_1      2
    7    C    Label_2      1
    8    C    Label_3      2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2021-10-15
      • 2019-03-03
      • 1970-01-01
      • 2013-01-12
      相关资源
      最近更新 更多