Skip to main content
 首页 » 编程设计

python之用 Pandas 标记列中的重复值

2025年05月04日13lyj

我有一个看起来像这样的 df:

email      is_new   col_n 
a@a        1           z  
a@a        1           x       
b@b        1           y  

我想更新第一个电子邮件地址实例的 is_new 列。新的 df 应该是这样的:

  email      is_new      col_n 
    a@a        0           z  
    a@a        1           x       
    b@b        0           y  

我已经尝试创建 IF 语句来检查电子邮件地址的数量,但它不起作用:

   1.  if df[df["email"].groupby().unique()> 1] ==True: 
        print('ook') 
 
   2. df.loc[df.groupby('email').groupby().unique(), 'is_new']=1 

请您参考如下方法:

让我们试试 groupby 和 cumcount:

df['is_new'] = df.groupby('email').cumcount().astype(bool).astype(int) 

或者,

df['is_new'] = df.groupby('email').cumcount().ne(0).astype(int) 

df 
  email  is_new col_n 
0   a@a       0     z 
1   a@a       1     x 
2   b@b       0     y 

详情
cumcount 返回一行中每个项目的递增计数:

df2 = pd.concat([df] * 2, ignore_index=True).sort_values('email') 

df2.groupby('email').cumcount() 
 
0    0 
1    1 
3    2 
4    3 
2    0 
5    1 
dtype: int64 

这只是一个代表性示例,但计数可以大于 1。我使用上述两种替代方法之一将所有计数 > 0 转换为 1:

df2.groupby('email').cumcount().ne(0).astype(int) 
# df2.groupby('email').cumcount().astype(bool).astype(int) 
 
0    0 
1    1 
3    1 
4    1 
2    0 
5    1 
dtype: int64