emax
emax

Reputation: 7245

Python: how to groupby a dataframe with column name numbered for the unique values of a column?

I have a dataframe that looks like the following where I have different number of case and 3 unique values for val.

df
     case    val
0     0       x
1     0       y 
2     0       z
3     1       x 
4     1       z
5     2       y

Now I would like to have a dataframe with a single row for each case and numbered columns for val. I would like something like this:

df1
      case     val0    val1    val2
0       0        x       y      z
1       1        x      nan     z
2       2       nan      y     nan

Upvotes: 1

Views: 34

Answers (1)

Corralien
Corralien

Reputation: 120401

Use pivot:

out = df.pivot(index='case', columns='val', values='val')
out.columns = [f'val{i}' for i in range(len(out.columns))]
>>> out
     val0 val1 val2
case               
0       x    y    z
1       x  NaN    z
2     NaN    y  NaN

Upvotes: 2

Related Questions