【问题标题】:Pandas DataFrame count duplicate rows and fill in columnPandas DataFrame 计算重复行并填充列
【发布时间】:2017-08-18 07:51:07
【问题描述】:

我创建了一个 DataFrame,现在需要计算每个重复行(例如 df['Gender']。假设性别“男性”出现两次,女性出现 3 次,我需要创建此列:

Gender   Occurrence
Male     1
Male     2
Female   1
Female   2
Female   3

有没有办法用 Pandas 做到这一点?

【问题讨论】:

    标签: python pandas dataframe duplicates


    【解决方案1】:

    Gender分组后使用cumcount方法:

    df = pd.DataFrame({'Gender':['Male','Male','Female','Female','Female']})   
    df['Occurrence'] = df.groupby('Gender').cumcount() + 1
    print(df)
    
       Gender  Occurrence
    0    Male           1
    1    Male           2
    2  Female           1
    3  Female           2
    4  Female           3
    

    计数从 0 开始,所以我在那里添加了 + 1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-25
      • 2022-01-23
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 2018-07-09
      • 2019-04-26
      • 2021-01-06
      相关资源
      最近更新 更多