【问题标题】:How to replace entries in a dataframe column with ordering如何用排序替换数据框列中的条目
【发布时间】:2021-07-02 16:15:18
【问题描述】:

我有以下数据框:

Item Produce Group
Mango Fruit
Spinach Vegetable
Peach Fruit
Squash Vegetable
Orange Fruit
Cauliflower Vegetable

如何从前一个数据帧创建以下数据帧?

Item Produce Group
Mango Fruit1
Spinach Vegetable1
Peach Fruit2
Squash Vegetable2
Orange Fruit3
Cauliflower Vegetable3

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以在每个组中使用groupbycumcount 元素:

    df['Produce Group'] + df.groupby('Produce Group').cumcount().add(1).astype(str)
    

    输出:

    0        Fruit1
    1    Vegetable1
    2        Fruit2
    3    Vegetable2
    4        Fruit3
    5    Vegetable3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2021-10-13
      • 2022-07-06
      相关资源
      最近更新 更多