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

标签 python pandas dataframe group-by pandas-groupby

我有一个看起来像这样的 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

最佳答案

让我们试试 groupbycumcount:

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

关于python - 用 Pandas 标记列中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116918/

相关文章:

python - 更改标签上的文本

python - Python 中使用 DATETIME 和变量的 SQLite 查询未按预期工作

python - 类型错误 : to_list_if_array() got an unexpected keyword argument 'convert_dtype'

python - 如何从 Dataframe 指定日期时间中的年、月、日?

python - 为什么我的最短哈密顿路径算法不是最优的?

python - 当我写入 CSV 时,如何隐藏 pandas to_datetime NaT?

python - 从 pandas 数据框中过滤元素进行统计分析

python - 根据数据框中的其他值更改 pandas 数据框的值

python - 应用函数创建多列作为参数的字符串

python - 是否可以在 Python 中创建带状态的嵌套函数?