按行切片将当前列值与不同列值进行比较

问题描述 投票:0回答:1

假设这样的数据框

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)中的值的次数。

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

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

python pandas slice
1个回答
0
投票

我已经用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
© www.soinside.com 2019 - 2024. All rights reserved.