Home > Software design >  Pandas group by column and convert to key:value pair
Pandas group by column and convert to key:value pair

Time:12-13

I want to convert DataFrame using pandas.

I would like to convert it into dictionary format like {'Plant Delivering ID': [Ship-To ID]}

there are multiple 'Ship-To ID' for single 'Plant Delivering ID'

My Original Data Format:

Original Data Format

I would like to convert it to:

converted Data Format

How do I convert it?

CodePudding user response:

Use pandas.DataFrame.groupby and then get the result of groupby with apply(list) at the end convert the result to dict with pandas.Series.to_dict.

df.groupby('Plant Delivering ID')['Ship-To-ID'].apply(list).to_dict()

CodePudding user response:

You can groupby then zip columns wrapped in dict()

df = df.groupby("Plant Delivering ID")["Ship-To-ID"].apply(list).reset_index()
df_dict = dict(zip(df["Plant Delivering ID"], df["Ship-To-ID"]))

CodePudding user response:

you could perform a group by on the Plant Delivering ID and bring everything into a dictionary.

Something like this:

dict = {k: list(v) for k, v in df.groupby('Plant Delivering ID')['Ship-To ID']}

Hope it helps!

The code is from this old answer.

  • Related