transpose pandas dataframe with dynamic columns

Advertisements

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)

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

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)

Leave a ReplyCancel reply