Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unpivot in pandas using a column that have mutiple value columns

So i have a dataframe frame like this

index type_of_product dt_of_product value_of_product size_of_product
1 A 01/02/22 23.1 1
1 B 01/03/22 23.2 2
1 C 01/04/22 23.3 2

And i need to unpivot the colum type_of_product with the values of dt_of_product, value_of_product and size_of_product

I tryed to use
pd.pivot(df, index = "index", column = "type_of_product", values = ["dt_of_product","value_of_product","size_of_product"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and want to get this desire output

index A_dt_of_product B_dt_of_product C_dt_of_product A_value_of_product B_value_of_product C_value_of_product A_size_of_product B_size_of_product C_size_of_product
1 01/02/22 01/03/22 01/04/22 23.1 23.2 23.3 1 2 2

Is there a way to do this in pandas with one pivot or do i have to do 3 pivots and merges all on them?

>Solution :

You can do:

df = df.pivot(index='index', 
              values=['dt_of_product', 'value_of_product', 'size_of_product'], 
              columns = ['type_of_product'])
df.columns = df.columns.swaplevel(0).map('_'.join)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading