Count occurences of True/False in column of dataframe
Use pd.Series.value_counts()
:
>> df = pd.DataFrame({'boolean_column': [True, False, True, False, True]})
>> df['boolean_column'].value_counts()
True 3
False 2
Name: boolean_column, dtype: int64
If you want to count False
and True
separately you can use pd.Series.sum()
+ ~
:
>> df['boolean_column'].values.sum() # True
3
>> (~df['boolean_column']).values.sum() # False
2
Counting the number of True Booleans in a Python List
True
is equal to 1
.
>>> sum([True, True, False, False, False, True])
3
How to count rows where condition is false Pandas?
If you want to count the rows where isValid
outputs False:
(~dataset['NUM'].apply(isValid)).sum()
output: 0
edit
m = dataset['NUM'].apply(isValid)
report["NUM"] = (~m).sum()
dataset2 = dataset[m]
Pandas count true boolean values per row
Apply sum
over columns axis:
df['count'] = df[['bool2', 'bool3']].sum(axis=1)
Output:
>>> df
num1 num2 bool1 bool2 bool3 count
0 20 30 True False True 1
1 10 5 False True True 2
Count number of trues in a numpy array in each row?
We can simply do this by providing an axis
argument to the sum
function:
arr.sum(axis=1)
How to count number of False values that precede at least one True with Numpy array?
As a oneliner:
import numpy as np
x = np.array([[0,0,1,0],[1,1,0,1],[1,1,1,1]], dtype='bool')
np.max((~x).cumsum(axis = 1) * x, axis = 1 )
# array([2, 1, 0])
To show the calculation:
not_x = ~x # Reverse the Trues and Falses
temp = not_x.cumsum( axis = 1 ) # cumsum the Falses by row.
temp
# array([[1, 2, 2, 3],
# [0, 0, 1, 1],
# [0, 0, 0, 0]])
temp *= x # Zero the result only where x is False
temp
# array([[0, 0, 2, 0],
# [0, 0, 0, 1],
# [0, 0, 0, 0]])
temp.max( axis = 1 ) # Find the max in each row.
# array([2, 1, 0])
Related Topics
Robot Framework Using Python, Key Press Without Selecting Any Button or Element in the Page
Type Conversion in Python Attributeerror: 'Str' Object Has No Attribute 'Astype'
Python Not Working in the Command Line of Git Bash
Calculating Manhattan Distance in Python in an 8-Puzzle Game
Changing Value in Data Frame Column in a Loop Python
How to Generate and Open an Outlook Email With Python (But Do Not Send)
Sharing a Complex Object Between Processes
Reading a CSV That Sometimes Contain Multiple Whitespaces
Tensorflow: Convert Tensor to Numpy Array Without .Eval() or Sess.Run()
Python Regex - How to Get Positions and Values of Matches
How to Connect to a Remote Windows Machine to Execute Commands Using Python
Cannot Convert the Series to <Class 'Int''>
How to Create an Automatically Updating Gui Using Tkinter
How to Copy a File to a Remote Server in Python Using Scp or Ssh
Django Development Server, How to Stop It When It Run in Background
How to Decompile a Compiled .Pyc File into a .Py File
Algorithm for Distributing a Number Between Certain Number of Chunks
Numpy: How to Pick Rows from Two 2D Arrays Based on Conditions in 1D Arrays