Pandas groupby并在列表中获得dict

roo*_*tit 3 python dictionary python-3.x pandas pandas-groupby

我正在尝试提取分组行数据以使用值将标签颜色绘制为另一个文件.

我的数据框如下所示.

df = pd.DataFrame({'x': [1, 4, 5], 'y': [3, 2, 5], 'label': [1.0, 1.0, 2.0]})

    x   y   label
0   1   3   1.0
1   4   2   1.0
2   5   5   2.0
Run Code Online (Sandbox Code Playgroud)

我想获得一组标签列表

{'1.0': [{'index': 0, 'x': 1, 'y': 3}, {'index': 1, 'x': 4, 'y': 2}],
 '2.0': [{'index': 2, 'x': 5, 'y': 5}]}
Run Code Online (Sandbox Code Playgroud)

这该怎么做?

cph*_*sto 5

df = pd.DataFrame({'x': [1, 4, 5], 'y': [3, 2, 5], 'label': [1.0, 1.0, 2.0]})
df['index'] = df.index
df
   label  x  y  index
0    1.0  1  3      0
1    1.0  4  2      1
2    2.0  5  5      2

df['dict']=df[['x','y','index']].to_dict("records")
df
   label  x  y  index                             dict
0    1.0  1  3      0  {u'y': 3, u'x': 1, u'index': 0}
1    1.0  4  2      1  {u'y': 2, u'x': 4, u'index': 1}
2    2.0  5  5      2  {u'y': 5, u'x': 5, u'index': 2}

df = df[['label','dict']]
df['label'] = df['label'].apply(str) #Converting integer column 'label' to string
df = df.groupby('label')['dict'].apply(list) 
desired_dict = df.to_dict()
desired_dict 
    {'1.0': [{'index': 0, 'x': 1, 'y': 3}, {'index': 1, 'x': 4, 'y': 2}],
     '2.0': [{'index': 2, 'x': 5, 'y': 5}]}
Run Code Online (Sandbox Code Playgroud)