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

Python 如何有效地检查数据帧每行中的连续值范围?,python,pandas,dataframe,Python,Pandas,Dataframe,假设我们有熊猫数据框,它看起来像这样: 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('d

假设我们有熊猫数据框,它看起来像这样:

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])
产出将是:

   A  a  B  b  C  c  D  d
1  0  a  1  b  1  c  0  d
2  0  a  0  b  1  c  1  d
3  1  a  0  b  0  c  0  d
4  0  a  1  b  1  c  1  d
所以现在我想得到这个数据帧的行,它至少包含两个0,例如在
A
B
C
D
列中 对于数据帧,索引为2和3的行满足以下条件:第二行的列
A
B
包含零,第三行的列
B
C
就足够了

如果我想找到三个或更多的连续零,那么找到这种序列的方法应该是有效的

最后我想得到一个布尔级数,它应该是这样的:

1 false
2 true
3 true
4 false

使用该序列作为原始数据帧的掩码。

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

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

1    False
2     True
3     True
4    False
dtype: bool
您可以使用和定义自己的函数来检查您的条件,如下所示:

# 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)
结果是:

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

感谢您指出
选择类型
方法。我不知道这件事。但我有一句话:如果出现负数,滚动
求和
可能会给出错误的结果。还有一个问题:为什么我最后需要
任何
方法?我考虑了
应用
方法,但怀疑循环列是否有效。顺便说一句,你的函数
zeros\u条件
没有变量。您将得到错误。@Alex Droidd在行上应用循环,列在本例中不是参数,但它们是外部定义的列表。这对我来说很好,你的错误是什么?好的,但如果我想找到三个或更多的零?@Alex Droidd在这种情况下,你的问题应该明确指出“我想要一个可以查找任意数量的连续零的解决方案,而不仅仅是两个。”请编辑你的问题,我会相应地编辑我的答案。