按组分组并选择每组的第一个、第二个和第四个成员?

3

相关链接: pandas dataframe groupby和获取第N行

我可以使用groupby方法,并选择前N个组成员:

df.groupby('columnA').head(N) 

但是如果我想要每个组的第一、二和第四个成员呢?
3个回答

5

GroupBy.nth 接收一个列表,因此您可以直接这样做:

df = pd.DataFrame({'A': list('aaaabbbb'), 'B': list('abcdefgh')})
df.groupby('A').nth([0, 1, 3])

   B
A   
a  a
a  b
a  d
b  e
b  f
b  h

# To get the grouper as a column, use as_index=False
df.groupby('A', as_index=False).nth([0, 1, 3])

   A  B
0  a  a
1  a  b
3  a  d
4  b  e
5  b  f
7  b  h

那些在负评的人:这真的是这里最差的答案吗? - cs95
我认为这是这里最好的答案。 - Cactus Philosopher

3

您可以执行

df.groupby('columnA').apply(lambda x : x.iloc[[has to 0,1,3],:]).reset_index(level=0,drop=True)

1
我猜索引应该是 [0, 1, 3] - cs95

2
df1 = df.groupby('columnA').head(4) 
df1.drop(df.groupby('columnA').head(4).index.values[2], axis=0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接