Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 column dataframe stacked data

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.

like image 521
wentworth Avatar asked May 09 '26 16:05

wentworth


2 Answers

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
like image 122
BENY Avatar answered May 11 '26 06:05

BENY


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
like image 35
jezrael Avatar answered May 11 '26 06:05

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!