Home > Enterprise >  Creating a dictionary of series from a dataframe
Creating a dictionary of series from a dataframe

Time:04-29

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')}  

enter image description here

enter image description here

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... enter image description here

Thank you
PS Here is a similar question link

CodePudding user response:

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}
  • Related