0

I have a data like this

A   12  
B   15
C    9
C   12
B   15 
A   24 
B    9
C    3
A    9

I would like to get the output using python code as shown below

A   B   C
12  15  9
24  15  12
9   9   3

Please help to get the python code.

BeRT2me
  • 12,699
  • 2
  • 13
  • 31

1 Answers1

1
pd.DataFrame(df.groupby(0).agg(list).to_dict()[1])

output:

    A   B   C
0   12  15  9
1   24  15  12
2   9   9   3
MoRe
  • 2,296
  • 2
  • 3
  • 23
  • 2
    That's not really an efficient or clean way to do it. Rather go with the way of the duplicate... – mozway Jul 24 '22 at 19:28
  • @mozway I test it and `pivot` and it was faster, so I add it... :) `8.09 ms ± 2.5 ms per loop` vs `2.35 ms ± 199 µs per loop` – MoRe Jul 24 '22 at 19:51
  • 1
    I tested on both a small and large dataframe and the `cumcount` way was faster, but fair enough both were quite similar (I would have expected a greater difference). Nevertheless, is too bad to have to convert to dict and again to DataFrame IMO. – mozway Jul 24 '22 at 20:06