Reputation: 395
I'm looking to turn two columns in a dataframe into a dictionary, column_a holds the item, and column_b has the description:
column_a column_b
---------------------
Furniture Table
Furniture Chair
Tech Laptop
Tech Screen
And the result should be:
{'Furniture':['Table','Chair'], 'Tech' : ['Laptop', 'Screen']}
Upvotes: 0
Views: 37
Reputation: 71
You'll want to use a groupby
statement, like this:
def turn_df_into_dict(df):
output_dict = {}
for name, group in df.groupby('column_a'):
output_dict[name] = group['column_b']
return output_dict
This should give you the intended output :)
Upvotes: 1
Reputation: 3285
Group into a list and then convert to dict:
dct = df.groupby('column_a')['column_b'].apply(list).to_dict()
Upvotes: 1