代码之家  ›  专栏  ›  技术社区  ›  akilat90

将列的值与大小逐渐减小的数组(或序列)进行比较

  •  1
  • akilat90  · 技术社区  · 8 年前

    df.values 也足够了)

    np.random.seed(42)
    df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b'])
    df
    
            a           b
    0   0.374540    0.950714
    1   0.731994    0.598658
    2   0.156019    0.155995
    3   0.058084    0.866176
    4   0.601115    0.708073
    5   0.020584    0.969910
    6   0.832443    0.212339
    7   0.181825    0.183405
    8   0.304242    0.524756
    9   0.431945    0.291229
    

    正确:如果有任何 b 特定后的值 a 一 价值 False:否则

    预期输出为: (请参阅以下部分行的说明)

           a           b      c
    0   0.374540    0.950714  True
    1   0.731994    0.598658  True
    2   0.156019    0.155995  True
    3   0.058084    0.866176  True   <- np.any(0.058084 < np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
    4   0.601115    0.708073  True   <- np.any(0.601115 < np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
    5   0.020584    0.969910  True   <- np.any(0.020584 < np.array([0.212339, 0.183405, 0.524756, 0.291229]))
    6   0.832443    0.212339  False  <- np.any(0.832443 < np.array([0.183405, 0.524756, 0.291229]))
    7   0.181825    0.183405  True   <- np.any(0.181825 < np.array([0.524756, 0.291229]))
    8   0.304242    0.524756  False  <- np.any(0.304242  < np.array([0.291229]))
    9   0.431945    0.291229  UNDEFINED <- Ignore this
    

    以上内容应该可以通过for循环实现,但是熊猫/numpy是如何实现的呢?

    我在尝试一种方法,将lambda函数应用于 一 但是我找不到一种方法来获得相应的 一 做某事的价值 np.any 如上所示的比较。(我后来发现 apply 只是for循环的语法糖)

    df['c'] = df['a'].apply(lambda x: np.any(x < df['b'].values[<i>:])) # Where <i> is the respective index value of x; which I didn't know how to find
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Divakar    8 年前

    诀窍是从下至上 b 查找累积最大值,并将其与中的相应值进行比较 a .

    因此,实施将是-

    a = df.a.values
    b = df.b.values
    out = a[:-1] < np.maximum.accumulate(b[::-1])[::-1][1:]
    

    pandas ,对应的是 df.cummax 对于 np.maximum.accumulate .

    In [45]: df
    Out[45]: 
              a         b
    0  0.374540  0.950714
    1  0.731994  0.598658
    2  0.156019  0.155995
    3  0.058084  0.866176
    4  0.601115  0.708073
    5  0.020584  0.969910
    6  0.832443  0.212339
    7  0.181825  0.183405
    8  0.304242  0.524756
    9  0.431945  0.291229
    
    In [46]: out
    Out[46]: array([ True,  True,  True,  True,  True,  True, False,  True, False], dtype=bool)
    
        2
  •  1
  •   akilat90    8 年前

    为了补充@Divakar的答案,熊猫们使用 cummax() 将是:

    df['c'] = df['a'] < df['b'][::-1].cummax()[::-1].reset_index(drop=True).shift(-1)
    
    print(df)  
    
            a         b      c
    0  0.374540  0.950714   True
    1  0.731994  0.598658   True
    2  0.156019  0.155995   True
    3  0.058084  0.866176   True
    4  0.601115  0.708073   True
    5  0.020584  0.969910   True
    6  0.832443  0.212339  False
    7  0.181825  0.183405   True
    8  0.304242  0.524756  False
    9  0.431945  0.291229  False