使用索引列表将某些组保留在GroupBy中

时间:2020-04-23 09:48:02

标签: python pandas pandas-groupby

你好StackOverflowers!

我有一个熊猫DataFrame

df = pd.DataFrame({
    'A':[1,1,2,1,3,3,1,6,3,5,1],
    'B':[10,10,300,10,30,40,20,10,30,45,20],
    'C':[20,20,20,20,15,20,15,15,15,15,15],
    'D':[10,20,30,40,80,10,20,50,30,10,70],
    'E':[10,10,10,22,22,3,4,5,9,0,1]
})

然后我在某些列上对其进行分组

groups = df.groupby(['A', 'B', 'C'])

我想根据groupby索引选择/过滤原始数据。

例如,我想从groupby中获得3个随机组合

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

与其遍历所有组len(indices)并每次都索引各自的indices值,不如从{{3}返回的字典中获得组keys的列表。 },并为每个索引单次调用GroupBy.groups

keys = list(groups.groups.keys())
# [(1, 10, 20), (1, 20, 15), (2, 300, 20)...
pd.concat([groups.get_group(keys[i]) for i in indices])

    A   B   C   D   E
6   1  20  15  20   4
10  1  20  15  70   1
5   3  40  20  10   3
4   3  30  15  80  22
8   3  30  15  30   9

答案 1 :(得分:0)

我能做的就是

groups = df.groupby(['A', 'B', 'C'])

indices = [1, 4, 3]
pd.concat([[df_group for names, df_group in groups][i] for i in indices])

结果为:

Out[24]: 
    A   B   C   D   E
6   1  20  15  20   4
10  1  20  15  70   1
5   3  40  20  10   3
4   3  30  15  80  22
8   3  30  15  30   9

我想知道是否有更优雅的方法,也许已经在pd.groupby()中实现了?