0

I have a table :

enter image description here

When I try to pivot in python:

df.pivot(columns = 'Type', values = 'Value')

it returns only columns from Type column with values but columns Col1-Col5 do not appear in my dataframe

In Power Query it's achieved very simple, I just choose column I want to pivot and values for this column: enter image description here

And after this operation I get following result:

enter image description here

How do I achieve the same result using pd.pivot ?

Thanks!

Adren
  • 83
  • 7

2 Answers2

0

In no way using pd.pivot. There is the pd.pivot_table function made for this case:

table = pd.pivot_table(df, values='Value', index=['Col1','Col2','Col3','Col4','Col5'], 
columns=['Type'], aggfunc=np.sum)
Vad1m
  • 389
  • 1
  • 14
0

You should be able to use pivot_table() to do this, same steps as outlined in this answer

res = df.pivot_table(values='Value', index=['Col1','Col2','Col3','Col4','Col5'], columns='Type')

This creates a multi-index dataframe, which you can then flatten:

res.reset_index(inplace=True)
res.columns.name = None
anant
  • 448
  • 3
  • 8
  • Getting 'DataError: No numeric types to aggregate' although 'Values' column has float numbers in it :( – Adren May 08 '20 at 21:37
  • can you post a subset of the dataset? ideally something easy to reproduce directly, these guidelines are a good reference point: https://stackoverflow.com/help/minimal-reproducible-example – anant May 08 '20 at 21:46