1

I have this data frame:

Name  type1  type2  type3  ...  typeN  color

John  8.7  0  NA  ...  56  blue

Andy  45  34  9.7  ...  NA  yellow

I need to change it to be like:

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

I'm a little bit confused about how to do that, any help please?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
LamaMo
  • 576
  • 2
  • 8
  • 19
  • 1
    You want to melt it. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html – CJR Jul 06 '19 at 21:38

2 Answers2

3

This is related to data reshaping. See workflow below using stack (alternative to melt),

Sample Data

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')

Output

    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
Mark Wang
  • 2,623
  • 7
  • 15
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


help-ukraine-now
  • 3,850
  • 4
  • 19
  • 36