每组中每第 n 行有一只熊猫

问题描述 投票:0回答:1

假设小组将有超过

n
的成员,我想从每个小组中取出第
n
行。我查看了https://pandas.pydata.org/pandas-docs/version/0.17.0/ generated/pandas.core.groupby.GroupBy.nth.html,但每组只需要一行。

例如:

    import pandas as pd
    x = pd.DataFrame.from_dict({'a': [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3], 'b': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]})


    a   b
0   1   1
1   1   2

2   2   3
3   2   4
4   2   5

5   3   6
6   3   7
7   3   8
8   3   9
9   3  10
10  3  11
11  3  12

如果我们保留每第二行,这将是期望的结果:

    a   b
1   1   2

3   2   4

6   3   7
8   3   9
10  3  11
python pandas dataframe group-by
1个回答
0
投票

用途:

out  = x[x.groupby('a').cumcount() % 2 == 1]
print (out)
    a   b
1   1   2
3   2   4
6   3   7
8   3   9
10  3  11
© www.soinside.com 2019 - 2024. All rights reserved.