Pandas group by column and convert to key:value pair

Question:

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?

Asked By: Namita Tare

||

Answers:

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"]))
Answered By: Jason Baker

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.

Answered By: AndreP

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()
Answered By: I'mahdi