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

transpose pandas dataframe with dynamic columns

I have a Input dataframe:

import pandas as pd

# Define the input data
data = {
    'ID':  [500, 500, 500, 500, 500, 400, 400, 400, 400, 300, 200],
    'item': ['A', 'B', 'C', 'D', 'E', 'A', 'B', 'C',  'E',   'D',    'E'],
    'Quantity': [1, 2, 3, 4, 5, 1, 2, 2, 1, 1, 5]
}
# Convert the input data to a Pandas DataFrame
df = pd.DataFrame(data)

enter image description here

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

I need to transform this input as you can see in below output example:

enter image description here

If you have any ideas please share. Thank you very much!

>Solution :

Try this:

pd.get_dummies(df, columns=['item'], prefix="", prefix_sep="").groupby(['ID'], as_index=False).sum().drop("Quantity", axis=1)
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