frequency seperate column in python

Viewed 25

I probably have a simple question, but I can't find the answer on this platform. I have a set of columns in my dataset df, like this:

A B C D
0 1 0 1
1 0 0 0
1 1 1 1
1 0 0 1

When I want the frequency of column A I have the following script:

df.A.value_counts()

And I get:

A 3
Name: A, dtype: int64

But now I want the counts of all the 4 columns. I've made the following script:

df[['A', 'B', 'C', 'D']].value_counts()

I want to get the output: A 3, B 2, C 1, D 3. But I only get the count of A, and not the other columns. What am I doing wrong here?

2 Answers

I think what you want is the number of ones if I interpret your output correctly. You can use the sum() function for this:

print(df.sum())

Gives me following output with your input:

A    3
B    2
C    1
D    3
dtype: int64

The function value_counts gives you the unique values in a column, which would give you 1 as output for any column. So, I assumed it is not what you want.

EDIT: If you want only a few columns you can filter the columns first and then apply the sum. Example:

# Select the columns; example without C
columns_you_want = ['A', 'B', 'D']

# Filter df before applying the sum function
print(df[columns_you_want].sum())

Output are only the wanted columns (no C):

A    3
B    2
D    3
dtype: int64

If you want to count specific values that are in few different columns you can use:

df[df == VALUE].count()

In this example this is:

df[df == 1].count()
Related