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. :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With