I have a pandas data frame that looks like this:
+------+------------+
| A | B |
+------+------------+
| ID | 1 |
| Date | 2019-04-04 |
| Name | Carl |
| ID | 2 |
| Date | 2019-04-05 |
| Name | Jane |
+------+------------+
I'm trying to make an output that looks like this:
+----+------------+------+
| ID | Date | Name |
+----+------------+------+
| 1 | 2019-04-04 | Carl |
| 2 | 2019-04-05 | Jane |
+----+------------+------+
I've tried transpose, pivot, and unstack methods but am really stuck.
Using cumcount create the key then pivot
df['C']=df.groupby('A').cumcount()
df.pivot(index='C',columns='A',values='B')
Out[118]:
A Date ID Name
C
0 2019-04-04 1 Carl
1 2019-04-05 2 Jane
Use GroupBy.cumcount with DataFrame.set_index and Series.unstack:
df = df.set_index([df.groupby('A').cumcount(), 'A'])['B'].unstack()
print (df)
A Date ID Name
0 2019-04-04 1 Carl
1 2019-04-05 2 Jane
If order of columns is important add :
df = (df.set_index([df.groupby('A').cumcount(), 'A'])['B']
.unstack()
.rename_axis(None, axis=1)
.reindex(['ID','Date','Name'], axis=1))
print (df)
ID Date Name
0 1 2019-04-04 Carl
1 2 2019-04-05 Jane
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With