首页 > 解决方案 > 如何查找下一个或更多行是否小于或等于数据框列的给定值?(熊猫,python)

问题描述

问题数据集:

datasetA = pd.DataFrame(data={'A':[1,100,80,10,8,8,9,11],
                              'B':[1,100,90,12,7,8,9,10],
                              'C':[1,100,80,13,12,11,12,13],
                              'D':[1,100,90,9,8,7,10,10]}
                              'E':[1,100,90,19,18,17,9,10]})
     A    B    C    D   E
0    1    1    1    1   1
1  100  100  100  100 100
2   80   90   80   90  80
3   10   12   13    9  19
4    8    7   12    8  18
5    8    8   11    7  17
6    9    9   12   10   9
7   11   10   13   10  10

我们需要检查值的数字是 10
,如果在一列中我们达到四个或更多连续行的值小于或等于 10,我们获取在这些行中首先下降到 =<10 的数字。如果数字稍后上升到 10 以上,那么我们获取零。

预期输出:

A B C D E
0 7 0 9 0

请记住,我需要计算超过 700 万列

标签: pythonpandascsvdataframetransformation

解决方案


使用带有自定义函数的 pandas DataFramerolling方法:

import pandas as pd


df = pd.DataFrame(data={'A':[1,100,80,10,8,8,9,11],
                        'B':[1,100,90,12,7,8,9,10],
                        'C':[1,100,80,13,12,11,12,13],
                        'D':[1,100,90,9,8,7,10,10]})
dfr = df.rolling(window=4).agg(lambda w: (w<=10).all())
dfr.dropna(inplace=True)

lst=[]
for c in list(df):
    try:
        #Retrieve first index we have a four consecutive numbers less than 10
        first_id = dfr.index[dfr[c] == 1].values.tolist()[0]
        # Consider the product of all 0s or 1s we have after
        v = dfr.loc[first_id:][c].prod()

        #Append  column, first index if all ones
        if v == 1:
            lst.append((c, df.loc[first_id-3][c]))
        # Otherwise append columns, 0
        else: 
            lst.append((c, 0))

    except:
        lst.append((c,0))

lst
[('A', 0), ('B', 7), ('C', 0), ('D', 9)]

推荐阅读