切片DataGrameGroupBy对象 [英] Slicing a DataGrameGroupBy object
问题描述
是否有一种切片DataFrameGroupBy对象的方法?
Is there a way to slice a DataFrameGroupBy object?
例如,如果我有:
df = pd.DataFrame({'A': [2, 1, 1, 3, 3], 'B': ['x', 'y', 'z', 'r', 'p']})
A B
0 2 x
1 1 y
2 1 z
3 3 r
4 3 p
dfg = df.groupby('A')
现在,返回的GroupBy对象由A中的值索引,我想选择它的一个子集,例如执行聚合.可能是这样的
Now, the returned GroupBy object is indexed by values from A, and I would like to select a subset of it, e.g. to perform aggregation. It could be something like
dfg.loc[1:2].agg(...)
,或者对于特定列,
dfg['B'].loc[1:2].agg(...)
编辑.更明确地说:通过对GroupBy对象进行切片,我的意思是仅访问组的子集.在上面的示例中,GroupBy对象将包含3个组,分别用于A = 1,A = 2和A =3.出于某些原因,我可能只对A = 1和A = 2的组感兴趣.
EDIT. To make it more clear: by slicing the GroupBy object I mean accessing only a subset of groups. In the above example, the GroupBy object will contain 3 groups, for A = 1, A = 2, and A = 3. For some reasons, I may only be interested in groups for A = 1 and A = 2.
推荐答案
您似乎需要使用iloc
的自定义函数-但是如果需要使用agg
,则返回合计值:
It seesm you need custom function with iloc
- but if use agg
is necessary return aggregate value:
df = df.groupby('A')['B'].agg(lambda x: ','.join(x.iloc[0:3]))
print (df)
A
1 y,z
2 x
3 r,p
Name: B, dtype: object
df = df.groupby('A')['B'].agg(lambda x: ','.join(x.iloc[1:3]))
print (df)
A
1 z
2
3 p
Name: B, dtype: object
对于多列:
df = pd.DataFrame({'A': [2, 1, 1, 3, 3],
'B': ['x', 'y', 'z', 'r', 'p'],
'C': ['g', 'y', 'y', 'u', 'k']})
print (df)
A B C
0 2 x g
1 1 y y
2 1 z y
3 3 r u
4 3 p k
df = df.groupby('A').agg(lambda x: ','.join(x.iloc[1:3]))
print (df)
B C
A
1 z y
2
3 p k
这篇关于切片DataGrameGroupBy对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!