如何基于唯一列值的首次出现获取行?

3

我有一个这样的数据框:

df
col1    col2    col3
 1        A       B
 1        D       R
 2        R       P
 2        D       F
 3        T       G
 1        R       S
 3        R       S

我希望获得col1前3个唯一值的数据框。如果某些col1值后来出现在数据框中,则会被忽略。
最终数据框应如下所示:
df
col1    col2    col3
 1        A       B
 1        D       R
 2        R       P
 2        D       F
 3        T       G

如何在pandas中以最有效的方式进行操作?


@jezrael 我想保留前三个唯一的col1值,drop_duplicates() 无法解决问题,如果有重复,请给我链接。 - Kallol
2
这个问题与链接的去重问题不同。 - Nathaniel
3个回答

1
使用Series.ne, Series.shiftSeries.cumsum创建连续的辅助组系列,然后通过布尔索引进行过滤:
N = 3
df = df[df.col1.ne(df.col1.shift()).cumsum() <= N]
print (df)
   col1 col2 col3
0     1    A    B
1     1    D    R
2     2    R    P
3     2    D    F
4     3    T    G

Detail:

print (df.col1.ne(df.col1.shift()).cumsum())
0    1
1    1
2    2
3    2
4    3
5    4
6    5
Name: col1, dtype: int32

1

这里有一个解决方案,它会在找到前三个不同的值后立即停止。

import pandas as pd
data="""
col1    col2    col3
 1        A       B
 1        D       R
 2        R       P
 2        D       F
 3        T       G
 1        R       S
 3        R       S
 """
df = pd.read_csv(pd.compat.StringIO(data), sep='\s+')
nbr = 3
dico={}
for index, row in df.iterrows():
    dico[row.col1]=True
    if len(dico.keys())==nbr:
        df = df[0:index+1]
        break

print(df)

  col1 col2 col3
0     1    A    B
1     1    D    R
2     2    R    P
3     2    D    F
4     3    T    G

@jezrael 我不是在说执行时间,而是指找到解决方案的速度快。抱歉我的英语。 - Frenchy
因为上一个操作的句子是“在pandas中如何以最有效的方式完成它?” :) - jezrael

1

您可以在pandas中使用duplicated方法:

mask1 = df.duplicated(keep = "first") # this line is to get the first occ.
mask2 = df.duplicated(keep = False)   # this line is to get the row that occ one single time.
mask =  ~mask1 | ~mask2
df[mask]

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