Night Walker
Night Walker

Reputation: 21260

DataFrame transform column values to new columns

I have following series:

project   id        type
First    130403725  PRODUCT      68
                    EMPTY         2
Six      130405706  PRODUCT      24
         132517244  PRODUCT      33
         132607436  PRODUCT      87

How I can transform type values to new columns:

                   PRODUCT  EMPTY
project   id        
First    130403725     68     2             
Six      130405706     24     0
         132517244     33     0
         132607436     87     0

Upvotes: 1

Views: 54

Answers (2)

jezrael
jezrael

Reputation: 862611

Use unstack, because MultiIndex Series:

s1 = s.unstack(fill_value=0)
print (s1)
type               EMPTY  PRODUCT
project id                       
First   130403725      2       68
Six     130405706      0       24
        132517244      0       33
        132607436      0       87

For DataFrame:

df = s.unstack(fill_value=0).reset_index().rename_axis(None, axis=1)
print (df)
  project         id  EMPTY  PRODUCT
0   First  130403725      2       68
1     Six  130405706      0       24
2     Six  132517244      0       33
3     Six  132607436      0       87

Upvotes: 1

johnpaton
johnpaton

Reputation: 765

This is a classic pivot table:

df_pivoted = df.pivot(index=["project", "id"], columns=["type"], values=[3])

I've used 3 as the index of the value column but it would be more clear if you would have named it.

Upvotes: 2

Related Questions