[英]To calculate the number of times the two dataframe columns are equal to -1 at the same time
I have two dataframe columns containing sequences of 0 and -1.我有两个包含 0 和 -1 序列的 dataframe 列。 Using Python command “count” I can calculate the number of times the 1st column equal '-1' ( =3 times) and the number of times the 2nd column equals '-1' ( =2 times).
使用 Python 命令“count”,我可以计算出第一列等于“-1”的次数(=3 次)和第二列等于“-1”的次数(=2 次)。 Actually, I would like to calculate the number of times that both columns x and y are equal to '-1' simultaneously ( = it should be equal to 1 in the given example)(something like calculating: count = df1['x'][df1['x'] == df1['y'] == -1]. count() but I cannot put 2 conditions directly in command 'count'..).
实际上,我想计算 x 和 y 列同时等于 '-1' 的次数(= 在给定示例中它应该等于 1)(类似于计算:count = df1['x' ][df1['x'] == df1['y'] == -1].count() 但我不能将 2 个条件直接放入命令 'count'..)。 Is there a simpe way to do it (using count or some other workaround)?
有没有一种简单的方法来做到这一点(使用计数或其他一些解决方法)? Thanks in advance!
提前致谢!
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
You can use eq
+ all
to get a boolean Series that returns True if both columns are equal to -1 at the same time.您可以使用
eq
+ all
获得 boolean 系列,如果两列同时等于 -1,则该系列返回 True。 Then sum
fetches the total:然后
sum
获取总数:
out = df1[['x','y']].eq(-1).all(axis=1).sum()
Output: Output:
1
Sum x
and y
, and count the ones where they add to -2.对
x
和y
求和,并计算它们加到 -2 的部分。 ie both are -1即两者都是-1
(df1.x + df1.y).eq(-2).sum()
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.