I have a dataframe that I want to turn into a dictionary of series.
Here is my dataframe and existing line of code that works except in one case (when the series has only one item).
df = pd.DataFrame({'col_1': ['Fruit', 'Apple', 'Pear','Orange','Vegtable','Pea','Lettus','Meat','Beef'],
'col_2': ['Fruit', .25, .25,.5,'Vegtable',.6,.4,'Meat',1],
'group':[1,1,1,1,2,2,2,3,3]})
dict_of_series = {g['col_2'].iat[0]:g.set_axis(g.iloc[0], axis=1).set_axis(g['col_1']).iloc[1:, 1:-1].squeeze() for i, g in df.groupby('group')}
The code works as long as a group has three rows, but occasionally I have 2 (as in meat where my beef value is disappearing). Specifically, this is what i want it to look like…

Thank you
PS Here is a similar question link
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try:
output = {x.iat[0,0]: pd.Series(x.set_index("col_1").iloc[1:,0], name=x.iat[0,0]) for _, x in df.groupby("group")}
>>> output
{'Fruit': col_1
Apple 0.25
Pear 0.25
Orange 0.5
Name: Fruit, dtype: object,
'Vegtable': col_1
Pea 0.6
Lettus 0.4
Name: Vegtable, dtype: object,
'Meat': col_1
Beef 1
Name: Meat, dtype: object}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

