【问题标题】:How to compare the row values of a column and update another column?如何比较一列的行值并更新另一列?
【发布时间】:2021-04-02 18:48:11
【问题描述】:

我有一个数据框列,如下所示:

items
apple
apple
apple
mango
mango
cherry

我正在尝试使用它生成一个新列(结果)。我比较行,如果前一行的值与当前行的值相同,那么结果列中的数字保持不变,否则它会增加。

item result
apple 1
apple 1
apple 1
mango 2
mango 2
cherry 3

我可以通过将项目列转换为列表来做到这一点,但想知道是否有更快的方法来做到这一点。

【问题讨论】:

    标签: python pandas dataframe compare rows


    【解决方案1】:

    使用.shift(),比较列,然后对布尔变量进行累积和:

    df["result"] = (df["items"] != df["items"].shift(1)).cumsum()
    print(df)
    

    打印:

        items  result
    0   apple       1
    1   apple       1
    2   apple       1
    3   mango       2
    4   mango       2
    5  cherry       3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多