python - Pandas - 按组比较当前年份与所有以前年份的值,如果它是累积最小值,则返回 True

标签 python pandas

我有一个具有以下结构的 Pandas 数据框

id    date         num        
243   2014-12-01   3
234   2014-12-01   2
243   2015-12-01   2
234   2016-12-01   4
243   2016-12-01   6
234   2017-12-01   5
243   2018-12-01   7
234   2018-12-01   10
243   2019-12-01   1
234   2019-12-01   12
243   2020-12-01   15
234   2020-12-01   5
我想添加另一列来比较字段 编号 来自 id 如果它小于前几年的任何值(对于每个 id )。例如, id 243 和 日期 2019-12-01 的值为 1。在这种情况下,新字段 将假定为 True,因为前几年没有任何值小于 id 243. 预期的数据框应如下所示:
id    date         num  flag         
243   2014-12-01   3      -
234   2014-12-01   2      -
243   2015-12-01   2      True
234   2016-12-01   4      False
243   2016-12-01   6      False
234   2017-12-01   5      False
243   2018-12-01   7      False
234   2018-12-01   10      False
243   2019-12-01   1      True
234   2019-12-01   12      False
243   2020-12-01   15      False
234   2020-12-01   5      False
我一直在寻找一个解决方案,让我可以将每一行与前几年的行进行比较。任何建议如何将每行值与几年前的值进行比较?
谢谢

最佳答案

  • 使用 .cummin按组获取累积最小值
  • 使用 .cumcount将每个组的第一个值返回为 -np.where
  • df['flag'] = (df['num'] == df.groupby(['id'])['num'].transform('cummin'))
    df['flag'] = np.where(df.groupby('id').cumcount() == 0, '-', df['flag'])
    df
    Out[1]: 
         id       date  num   flag
    0   243 2014-12-01    3      -
    1   234 2014-12-01    2      -
    2   243 2015-12-01    2   True
    3   234 2016-12-01    4  False
    4   243 2016-12-01    6  False
    5   234 2017-12-01    5  False
    6   243 2018-12-01    7  False
    7   234 2018-12-01   10  False
    8   243 2019-12-01    1   True
    9   234 2019-12-01   12  False
    10  243 2020-12-01   15  False
    11  234 2020-12-01    5  False
    
    小注:代替 np.where() ,您还可以使用:
    df['flag'] = df['flag'].where(df.groupby('id').cumcount() != 0, '-')
    
    这基本上做完全相同的事情。
    在其中一行代码中:
    (df.num == df.groupby('id').num.cummin()).where(df.groupby('id').cumcount() != 0, '-')
    

    关于python - Pandas - 按组比较当前年份与所有以前年份的值,如果它是累积最小值,则返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64253445/

    相关文章:

    python - R 对一行中的重复项进行子集化并返回重复项和索引

    python - 在python中通过其索引和数组切片数据框

    python - 如何在类的 __init__ 函数中使用 Canvas 参数?

    python - 将多分隔符列拆分为多列

    python - pandas 展开字母数字字符进行迭代

    python - 如何使用 None 启动新列并有条件地使用元组更新其值?

    python - 属性错误 : 'Worksheet' object has no attribute 'set_column'

    python - 在 Matplotlib 中循环创建子图?

    python - Django REST Framework - 通过路由器将模型传递给 ViewSet

    Python 类装饰器参数