从数据框创建系列字典

Creating a dictionary of series from a dataframe

我有一个数据框,我想把它变成一个系列字典。 这是我的数据框和现有的代码行,除了在一种情况下(当系列只有一个项目时)。

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

只要一个组有三行,代码就可以工作,但偶尔我有 2 行(比如我的牛肉价值正在消失的肉)。具体来说,这就是我想要的样子......

谢谢
PS这里有一个类似的问题

尝试:

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}