some_programmer
some_programmer

Reputation: 3528

How to print value_count() values from different columns together?

I have a dataset that has different columns. I have applied value_counts() in order to print the counts of unique values. I have applied the same for 6 different columns as follows:

complete_data['Sex'].value_counts()
complete_data['Survived'].value_counts()
complete_data['Parch'].value_counts()
complete_data['Pclass'].value_counts()
complete_data['SibSp'].value_counts()
complete_data['Embarked'].value_counts() 

I would like to know if there is a way wherein all the different columns (Sex, survived etc) can all be combined in one line of code rather than 6 different lines as above.

Thanks

Upvotes: 3

Views: 1628

Answers (3)

Valdi_Bo
Valdi_Bo

Reputation: 30991

Assume the source DataFrame as follows:

df = pd.DataFrame(data=[[5, 5, 2, 1], [0, 2, 6, 7], [6, 1, 4, 6],
    [7, 0, 7, 3], [0, 3, 1, 2], [1, 5, 6, 0]], columns=list('ABCD'))

Then, to count value_counts for all columns, you can apply value_counts to the DataFrame, actually to all columns:

df.apply(pd.Series.value_counts).fillna(0, downcast='infer')

For my source data, the result is:

   A  B  C  D
0  2  1  0  1
1  1  1  1  1
2  0  1  1  1
3  0  1  0  1
4  0  0  1  0
5  1  2  0  0
6  1  0  2  1
7  1  0  1  1

i.e. A column has 2 cases of 0, 1 case of 1, 5, 6 and 7, similarly for other columns.

Upvotes: 1

Ben Pap
Ben Pap

Reputation: 2579

df[['Sex', 'Survived', 'Parch', 'Pclass', 'Sibsp', 'Embarked']].apply(pd.value_counts)

This will give you back a df with value counts for each.

Upvotes: 3

Chris Adams
Chris Adams

Reputation: 18647

You could use a for loop:

for col in complete_data:
    print(complete_data[col].value_counts(), '\n')

Upvotes: 3

Related Questions