Skip to main content
 首页 » 编程设计

python之按组 pandas 选择每 n 个观察值

2025年05月04日12傻小

我有一些生成数据框的代码。我希望能够根据 df1 和 df2 中的“组”分类选择每第 n 个。

    import pandas as pd 
    data = [['Orange',11], ['Orange',12], ['Orange',13], ['Orange',14]  
            ['Orange',15], ['Orange',16], ['Orange',17], ['Orange',18],  
            ['StrawBerry',22], ['StrawBerry',23], ['StrawBerry',24],  
            ['StrawBerry',25], ['StrawBerry',26], ['StrawBerry',27]] 
    df = pd.DataFrame(data,columns=['Fruit', 'Score']) 
    df 
 
    #Here I start from the 1st row and then move to the fourth and then  
    #and so forth by Fruit. 
    Output1data = [['Orange',11], ['Orange',14], ['Orange',17],  
                  ['StrawBerry',22], ['StrawBerry',25]] 
    df1 = pd.DataFrame(Output1data,columns=['Fruit','Score']) 
    df1 
 
    #Here I start from the second row onwards and then move to the fifth and  
    #then eighth and so forth by Fruit  
    Output2data = [['Orange',12], ['Orange',15], ['Orange',18],  
                   ['StrawBerry',23], ['StrawBerry',26]] 
    df2 = pd.DataFrame(Output2data,columns=['Fruit','Score']) 
    df2 

请告诉我是否可以使用组分类来执行此操作,因为我需要为给定的起点选择每第 n 行?

非常感谢。真的很感激这一点。

请您参考如下方法:

使用GroupBy.cumcount用 3 对助手 Series 取模,然后按 boolean indexing 过滤:

s = df.groupby('Fruit')['Fruit'].cumcount() % 3 
print (s) 
0     0 
1     1 
2     2 
3     0 
4     1 
5     2 
6     0 
7     1 
8     0 
9     1 
10    2 
11    0 
12    1 
13    2 
dtype: int64 
 
df1 = df[s == 0] 
print (df1) 
         Fruit  Score 
0       Orange     11 
3       Orange     14 
6       Orange     17 
8   StrawBerry     22 
11  StrawBerry     25 
 
df2 = df[s == 1] 
print (df2) 
         Fruit  Score 
1       Orange     12 
4       Orange     15 
7       Orange     18 
9   StrawBerry     23 
12  StrawBerry     26