【发布时间】:2014-02-02 09:52:51
【问题描述】:
我有一个数据框如下:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : range(1,9),
'code' : ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'colour': ['black', 'white','white','white',
'black', 'black', 'white', 'white'],
'amount' : np.random.randn(8)}, columns= ['id','code','colour','amount'])
我希望能够通过code 和colour 对ids 进行分组,然后根据amount 对它们进行排序。我知道如何groupby():
df.groupby(['code','colour']).head(5)
id code colour amount
code colour
one black 0 1 one black -0.117307
white 1 2 one white 1.653216
6 7 one white 0.817205
three black 5 6 three black 0.567162
white 3 4 three white 0.579074
two black 4 5 two black -1.683988
white 2 3 two white -0.457722
7 8 two white -1.277020
但是,我想要的输出如下,其中我有两列:1.code/colour包含键字符串和 2.id:amount 包含 id - amount 以降序排列的元组 wrt amount :
code/colour id:amount
one/black {1:-0.117307}
one/white {2:1.653216, 7:0.817205}
three/black {6:0.567162}
three/white {4:0.579074}
two/black {5:-1.683988}
two/white {3:-0.457722, 8:-1.277020}
如何将上面显示的DataFrameGroupBy 对象转换为我想要的格式?或者,我不应该首先使用groupby()吗?
编辑: 虽然不是指定的格式,但下面的代码给了我想要的功能:
groups = dict(list(df.groupby(['code','colour'])))
groups['one','white']
id code colour amount
1 2 one white 1.331766
6 7 one white 0.808739
如何减少组以仅包含 id 和 amount 列?
【问题讨论】:
标签: python group-by pandas dataframe