将第二个条目保留在数据框中

时间:2019-12-10 13:01:34

标签: pandas dataframe

我正在向您展示示例数据集和所需的输出。

ID号

1   50

1   49

1   48

2   47

2   40

2   31

3   60

3   51

3   42

示例输出

1  49

2  40

3  51

我想为数据集中的每个组保留第二个条目。我已经按ID对它们进行了分组,但是我不希望每个ID保留第二个条目,然后从ID中删除所有重复项。

2 个答案:

答案 0 :(得分:3)

GroupBy.nth1用于第二行,因为python从0开始计数:

df1 = df.groupby('ID', as_index=False).nth(1)
print (df1)
   ID  number
1   1      49
4   2      40
7   3      51

另一个带有GroupBy.cumcount的计数器和boolean indexing过滤解决方案:

df1 = df[df.groupby('ID').cumcount() == 1]

详细信息

print (df.groupby('ID').cumcount())
0    0
1    1
2    2
3    0
4    1
5    2
6    0
7    1
8    2
dtype: int64

编辑:第二个最大值的解决方案-s首先进行排序,然后获取第二行-每个组的值必须唯一:

df = (df.sort_values(['ID','number'], ascending=[True, False])
        .groupby('ID', as_index=False)
        .nth(1))

print (df)
   ID  number
1   1      49
4   2      40
7   3      51

如果要第二个最大值(如果存在重复项),请添加DataFrame.drop_duplicates

print (df)

   ID  number
0   1      50 <-first max
1   1      50 <-first max
2   1      48 <-second max
3   2      47
4   2      40
5   2      31
6   3      60
7   3      51
8   3      42

df3 = (df.drop_duplicates(['ID','number'])
       .sort_values(['ID','number'], ascending=[True, False])
       .groupby('ID', as_index=False)
       .nth(1))

print (df3)
   ID  number
2   1      48
4   2      40
7   3      51

答案 1 :(得分:2)

如果是这种情况,我们可以使用duplicated + drop_duplicates

df=df[df.duplicated('ID')].drop_duplicates('ID')
   ID  number
1   1      49
4   2      40
7   3      51

灵活的解决方案cumcount

df[df.groupby('ID').cumcount()==1].copy()
   ID  number
1   1      49
4   2      40
7   3      51