【问题标题】:How to change the columns into rows [duplicate]如何将列更改为行[重复]
【发布时间】:2019-11-16 22:58:01
【问题描述】:

我有这个数据框:

Name  type1  type2  type3  ...  typeN  color

John  8.7  0  NA  ...  56  blue

Andy  45  34  9.7  ...  NA  yellow

我需要把它改成这样:

color  typeName  Name  value
blue  type1  John  8.7
blue  type2  John  0
blue  type3  John  NA
.
.
.
blue  typeN  John  56
yellow  type1  Andy  45
yellow  type2  Andy  34
yellow  type3  Andy  9.7
.
.
.
yellow  typeN  Andy  NA

我有点困惑如何做到这一点,请帮忙?

【问题讨论】:

标签: python pandas rows


【解决方案1】:

这与数据重塑有关。请参阅下面使用堆栈的工作流程(替代熔化),

样本数据

df=pd.DataFrame({'Name':['John','Andy'], 'type1':[8.7,45],'type2':[0,34], 'color':['blue','yellow']})
result = df.set_index(['Name','color'])
           .rename_axis('typeName',axis=1)
           .stack(dropna=False)
           .reset_index(name='value')

输出

    Name    color   typeName    value
0   John    blue    type1   8.7
1   John    blue    type2   0.0
2   Andy    yellow  type1   45.0
3   Andy    yellow  type2   34.0

【讨论】:

    【解决方案2】:
    pd.melt(df, id_vars=['Name', 'color'], var_name='typeName')
    

        Name    color   typeName    value
    0   John    blue    type1       8.7
    1   Andy    yellow  type1       45.0
    2   John    blue    type2       0.0
    3   Andy    yellow  type2       34.0
    4   John    blue    type3       NaN
    5   Andy    yellow  type3       9.7
    6   John    blue    typeN       56.0
    7   Andy    yellow  typeN       NaN
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2016-08-30
      • 2015-08-18
      • 2017-11-05
      • 1970-01-01
      • 2019-06-30
      • 2013-05-07
      相关资源
      最近更新 更多