1

I have a large dataframe (around 100K rows). Structure is like this -

df={'time':[1,1,1],'counter':['A','B','C'],'ID':[0,0,0],'value':[1,1,3]}
In [11]: pd.DataFrame(df)
Out[11]: 
   ID counter  time  value
0   0       A     1      1
1   0       B     1      1
2   0       C     1      3

I want to create a pivot that uses Column = Counter as the column names. So something like -

    ID time A B C 
  0 0  1    1 1 3

How can I do this in an fast and efficient way. Thanks

rfguy
  • 149
  • 1
  • 3
  • 11

1 Answers1

2

Use DataFrame.pivot_table:

new_df=df.pivot_table(columns='counter',index=['ID','time'],values='value').reset_index().rename_axis(columns=None)
print(new_df)

   ID  time  A  B  C
0   0     1  1  1  3
ansev
  • 30,322
  • 5
  • 17
  • 31