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

Tip*_*ena 3 python group-by pandas pandas-groupby

相关:pandas dataframe groupby 并获取第 n 行

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

df.groupby('columnA').head(N) 
Run Code Online (Sandbox Code Playgroud)

但是如果我想要每组的第一、第二和第四个成员怎么办?

cs9*_*s95 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
Run Code Online (Sandbox Code Playgroud)

# 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
Run Code Online (Sandbox Code Playgroud)