【问题标题】:Compare current column value to different column value by row slices按行切片将当前列值与不同列值进行比较
【发布时间】:2020-02-09 20:45:07
【问题描述】:

假设这样的数据框

In [5]: data = pd.DataFrame([[9,4],[5,4],[1,3],[26,7]])                         

In [6]: data                                                                    
Out[6]: 
    0  1
0   9  4
1   5  4
2   1  3
3  26  7

我想计算第 0 列上 2 的滚动窗口/切片中的值大于或等于第 1 列 (4) 中的值的次数。

在第 1 列的第一个数字 4 上,第 0 列上的 2 切片产生 5 和 1,因此输出将为 2,因为这两个数字都大于 4,然后在第二个 4 上,第 0 列上的下一个切片值将是 1 和 26,因此输出将为 1,因为只有 26 大于 4 而不是 1。我不能使用滚动窗口,因为没有实现对滚动窗口值的迭代。

我需要前 n 行的切片,然后我可以迭代、比较和计算该切片中的任何值在当前行之上的次数。

【问题讨论】:

    标签: python pandas slice


    【解决方案1】:

    我使用list 完成了此操作,而不是在data frame 中执行此操作。检查下面的代码:

    list1, list2 = df['0'].values.tolist(),  df['1'].values.tolist()
    outList = []
    for ix in range(len(list1)):
        if ix < len(list1) - 2:
            if list2[ix] < list1[ix + 1] and list2[ix] < list1[ix + 2]:
                outList.append(2)
            elif list2[ix] < list1[ix + 1] or list2[ix] < list1[ix + 2]:
                outList.append(1)
            else:
                outList.append(0)
        else:
            outList.append(0)
    
    df['2_rows_forward_moving_tag'] = pd.Series(outList) 
    

    输出:

        0  1  2_rows_forward_moving_tag
    0   9  4                          1
    1   5  4                          1
    2   1  3                          0
    3  26  7                          0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      相关资源
      最近更新 更多