如何有效地检查每行pandas数据帧中的连续值范围?

2024-05-16 04:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有pandas数据帧,如下所示:

df = pd.DataFrame(
        {'A': [0, 0, 1, 0],
        'a': list('aaaa'),
        'B': [1, 0 , 0, 1],
        'b': list('bbbb'),
        'C': [1, 1, 0, 1],
        'c': list('cccc'),
        'D': [0, 1, 0, 1],
        'd': list('dddd')},
        index=[1, 2, 3, 4])

输出将是:

^{pr2}$

所以现在我想得到这个数据帧的行,例如至少在ABCD列中按顺序包含两个0。
对于上面的dataframe,索引为2和3的行满足以下条件:第二行的列AB包含零,第三行的BC就足够了。在

如果我想找到三个或更多个连续的零,那么找到这个序列的方法应该是可行的。在

所以最终我想要一个布尔级数,它应该看起来像:

1 false
2 true
3 true
4 false

将该系列用作原始数据帧的掩码。在


Tags: 数据falsetruedataframepandasdfindex顺序
3条回答

您可以使用pandas' apply function并定义自己的函数来检查您的条件,如下所示:

# columns you want to check. Note they have to be in the right order!!
columns = ["A", "B", "C", "D"]

# Custom function you apply over df, takes a row as input
def zeros_condition(row):
    # loop over the columns.
    for n in range(len(columns)-1): 
        # return true if 0s in two adjacent columns, else false
        if row[columns[n]] == row[columns[n+1]] == 0:
            return True
    return False

result = df.apply(zeros_condition, axis=1)

结果是:

^{pr2}$

选择数字列,然后使用shift进行比较:

u = df.select_dtypes(np.number).T
((u == u.shift()) & (u == 0)).any()

1    False
2     True
3     True
4    False
dtype: bool

从cs95建立的数据

u = df.select_dtypes(np.number).T

(u.rolling(2).sum()==0).any()
Out[404]: 
1    False
2     True
3     True
4    False
dtype: bool

相关问题 更多 >