Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:How to count specific values in specific columns in a dataframe

I have a particular csv for eg:

col1 col2 col3 col4

a    1    2     3

b    1    2     1 

c    1    1     3

d    3    1     2 

I want to count number of a particular value for eg. 1 in col2, col3 and col4

I am using the following code using pandas

import pandas as pd

fname = input('Enter the filename:')
df = pd.read_csv (fname, header='infer')
one = df.iloc[:,1:4].value_counts(normalize=False).loc[1]

It is showing error but when I am doing the same for a particular defined column the code is running properly

import pandas as pd
fname = input('Enter the filename:')
df = pd.read_csv (fname, header='infer')
one = df[col1].value_counts(normalize=False).loc[1]

I want the following output

col2 3

col3 2

col4 1

Any help or tips would be greatly appreciated! Thank you in advance. :)

like image 246
userAD Avatar asked Sep 20 '18 11:09

userAD


1 Answers

Use eq with desired value i.e. 1 and then sum as:

df1[['col2', 'col3', 'col4']].eq(1).sum()

col2    3
col3    2
col4    1
dtype: int64
like image 136
Space Impact Avatar answered Sep 22 '22 00:09

Space Impact