【问题标题】:How to use rolling function to compare the elements如何使用滚动功能比较元素
【发布时间】:2022-07-31 09:06:58
【问题描述】:

我想用pandasrolling函数比较第一个元素是否小于第二个。我认为以下代码应该可以工作:

import numpy as np
import pandas as pd
df = pd.DataFrame(data=np.random.randint(0,10,10), columns=['temperature'])
df.rolling(window=2).apply(lambda x: x[0] < x[1])

但它不起作用。相反,我收到一条错误消息:

ValueError: 0 is not in range

有人知道是什么原因造成的吗?

更新: 我知道我可以使用diff 函数,但我真正想做的是这样的

df.rolling(window=3).apply(lambda x: x[0] < x[1] < x[2])

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    用 x.iloc[n] 替换 x[n] 应该可以工作(使用位置索引)

    import numpy as np
    import pandas as pd
    df = pd.DataFrame(data=np.random.randint(0,10,10), columns=['temperature'])
    df['increasing'] = df.rolling(window=2).apply(lambda x: x.iloc[0] < x.iloc[1])
    
       temperature  increasing
    0            8         NaN
    1            9         1.0
    2            0         0.0
    3            3         1.0
    4            8         1.0
    5            7         0.0
    6            7         0.0
    7            8         1.0
    8            7         0.0
    9            6         0.0
    

    为什么?:

    您的 lambda 函数中“x”的值如下所示:

    第一次迭代:

    指数温度
    0 8
    1 9

    第二次迭代:

    指数温度
    1 9
    2 0

    第三次迭代:

    指数温度
    2 0
    3 3

    第一次迭代有效,因为索引 0 和 1 可用(所以 x[0] &lt; x[1] 工作正常)。但是,在第二次迭代中,索引 0 不可用并且 x[0] 因您的 ValueError 而失败。我的解决方案使用位置索引(使用 .iloc)并忽略那些索引值(请参阅https://pandas.pydata.org/docs/user_guide/indexing.html)。

    这也是为什么您的代码可以在两行中正常工作的原因,例如

    df = pd.DataFrame(data=np.random.randint(0,10,2), columns=['temperature'])
    df.rolling(window=2).apply(lambda x: x[0] < x[1])
    

    【讨论】:

      【解决方案2】:

      IIUC,如果确定温度是否高于之前的温度,你想达到什么效果?

      你可以使用diff:

      df['temperature'].diff().gt(0)
      

      检查连续增加:

      N = 3  # 3 consecutive values are increasing (= 2 increases)
      df['increases2'] = df['temperature'].diff().gt(0).rolling(N-1).sum().eq(N-1)
      

      示例:

      >>> df['increases'] = df['temperature'].diff().gt(0)
      >>> df['increases2'] = df['temperature'].diff().gt(0).rolling(N-1).sum().eq(N-1)
      
         temperature  increases  increases2
      0            7      False       False
      1            7      False       False
      2            9       True       False
      3            1      False       False
      4            7       True       False
      5            0      False       False
      6            6       True       False
      7            9       True        True
      8            9      False       False
      9            7      False       False
      

      【讨论】:

      • 我想做的是这样的:df.rolling(window=3).apply(lambda x: x[0] &lt; x[1] &lt; x[2])
      • @Michael 然后在后面添加rollingdf['temperature'].diff().gt(0).rolling(2).sum().eq(2)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2013-02-26
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2018-03-07
      • 2012-05-08
      相关资源
      最近更新 更多