0

I have a following DataFrame:

id A B
1 Elle 567998
1 Rand 1234
1 Danny 5678
2 Rand 91011
2 Danny 121314
2 Elle 151413

How do I transform it into a following dataframe:

A 1 2
Elle 567998 151413
Rand 1234 91011
Danny 5678 121314

I've tried using loops and Series but nothing worked.

mirkap
  • 7
  • 1
  • 4

1 Answers1

1

Try this :

df.groupby('A')['B'].apply(lambda x: pd.Series(list(x))).unstack()
AfterFray
  • 1,751
  • 3
  • 17
  • 22
  • Thanks, this works perfectly. The only issue is that the new columns, which should be named after the id column, in this case 1 and 2, are named 0 and 1. How would I change that? – mirkap Dec 09 '21 at 07:39