计算两个dataframe列同时等于-1的次数

To calculate the number of times the two dataframe columns are equal to -1 at the same time

我有两个包含 0 和 -1 序列的数据框列。 使用 Python 命令“count”,我可以计算出第一列等于“-1”的次数(=3 次)和第二列等于“-1”的次数(=2 次)。实际上,我想计算 x 和 y 列同时等于 '-1' 的次数(= 在给定示例中它应该等于 1)(类似于计算:count = df1['x'][df1['x'] == df1['y'] == -1].count() 但我不能直接在命令中输入 2 个条件 'count'..)。 有没有一种简单的方法来做到这一点(使用计数或其他一些解决方法)? 提前致谢!

import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
df1 = pd.DataFrame({
"x":     [0, 0, 0, -1 , 0, -1,  0, 0, 0, 0 , 0, 0,  0, -1, 0],
"y":     [0, 0, 0,  0 , 0, 0,  -1, 0, 0, 0 , 0, 0,  0, -1, 0],   
})
df1
    x   y
0   0   0
1   0   0
2   0   0
3   -1  0
4   0   0
5   -1  0
6   0   -1
7   0   0
8   0   0
9   0   0
10  0   0
11  0   0
12  0   0
13  -1  -1
14  0   0

count = df1['x'][df1['x'] == -1]. count()
count

3

count = df1['y'][df1['y'] == -1]. count()
count

2

您可以使用 eq + all 得到一个布尔系列,如果两列同时等于 -1,则 returns 为真。然后 sum 获取总数:

out = df1[['x','y']].eq(-1).all(axis=1).sum()

输出:

1

xy相加,然后计算它们加到-2的地方。即两者都是-1

 (df1.x + df1.y).eq(-2).sum()
 1