【问题标题】:How can i find unique record in python by row count?如何按行数在 python 中找到唯一记录?
【发布时间】:2020-02-10 20:50:42
【问题描述】:

df:

  Country  state      item 
0 Germany  Augsburg   Car
1 Spain    Madrid     Bike
2 Italy    Milan      Steel
3 Paris    Lyon       Bike
4 Italy    Milan      Steel
5 Germany  Augsburg   Car

在上面的数据框中,如果我们取唯一记录外观。

  Country  state      item  Appeared
0 Germany  Augsburg   Car     1
1 Spain    Madrid     Bike    1
2 Italy    Milan      Steel   1
3 Paris    Lyon       Bike    1
4 Italy    Milan      Steel   2
5 Germany  Augsburg   Car     2

因为第没有。 4 和 5 第二次出现,我想更改它们的项目名称以区分两个记录。如果记录在数据中出现多次,项目名称应重命名为第一次出现的 Item_A 和第二次出现的 Item_B。 .. 输出:

Country  state      item  Appeared
0 Germany  Augsburg   Car_A   1
1 Spain    Madrid     Bike    1
2 Italy    Milan      Steel_A 1
3 Paris    Lyon       Bike    1
4 Italy    Milan      Stee_B  2
5 Germany  Augsburg   Car_B   2

【问题讨论】:

    标签: python python-3.x pandas python-2.7


    【解决方案1】:

    可以先通过groupby().cumcount得到Appreared列,然后加上后缀:

    # unique values
    duplicates = df.duplicated(keep=False)
    
    # Appearance count
    df['Appeared'] = df.groupby([*df]).cumcount().add(1)
    
    # add the suffixes
    suffixes = np.array(list('ABC'))
    df.loc[duplicates, 'item'] = df['item'] + '_' + suffixes[df.Appeared-1]
    

    输出:

       Country     state     item  Appeared
    0  Germany  Augsburg    Car_A         1
    1    Spain    Madrid     Bike         1
    2    Italy     Milan  Steel_A         1
    3    Paris      Lyon     Bike         1
    4    Italy     Milan  Steel_B         2
    5  Germany  Augsburg    Car_B         2
    

    【讨论】:

    • 你也可以用{i: chr(i+64) for i in range(1, 26)}映射出现列:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2018-04-11
    相关资源
    最近更新 更多