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:
I would like to convert it to:
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.