Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of False or True in a column in pandas

given

patient_id  test_result has_cancer 0   79452   Negative    False 1   81667   Positive    True 2   76297   Negative    False 3   36593   Negative    False 4   53717   Negative    False 5   67134   Negative    False 6   40436   Negative    False 

how to count False or True in a column , in python?

I had been trying:

# number of patients with cancer  number_of_patients_with_cancer= (df["has_cancer"]==True).count() print(number_of_patients_with_cancer) 
like image 481
Ney J Torres Avatar asked Nov 30 '18 03:11

Ney J Torres


People also ask

How do you count occurrences in a column in pandas?

Using the size() or count() method with pandas. DataFrame. groupby() will generate the count of a number of occurrences of data present in a particular column of the dataframe.

How do you count true and false values in Python?

Use count_nonzero() to count True elements in NumPy array In Python, False is equivalent to 0 , whereas True is equivalent to 1 i.e. a non-zero value. Numpy module provides a function count_nonzero(arr, axis=None), which returns the count of non zero values in a given numpy array.

How do you count the number of repeated values in pandas?

You can count the number of duplicate rows by counting True in pandas. Series obtained with duplicated() . The number of True can be counted with sum() method. If you want to count the number of False (= the number of non-duplicate rows), you can invert it with negation ~ and then count True with sum() .


1 Answers

So you need value_counts ?

df.col_name.value_counts() Out[345]:  False    6 True     1 Name: has_cancer, dtype: int64 
like image 193
BENY Avatar answered Oct 02 '22 15:10

BENY