2

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?

Namita Tare
  • 123
  • 9

3 Answers3

1

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"]))
Jason Baker
  • 3,170
  • 2
  • 12
  • 15
1

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.

AndreP
  • 105
  • 1
  • 5
1

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()
I'mahdi
  • 23,382
  • 5
  • 22
  • 30