Pivot by count of values in multiple columns pandas

Ralph Del Negro :

I have a dataframe where multiple columns have a 0, 1, or 5 as the values. I want to be able to pivot the table so that the columns are 0, 1 and 5, the rows are the original column names and the values are the count of each time a 0, 1, or 5 appeared in the original column.

the original table:

col1 col2 col3 col4
0    1    0    5
1    1    0    1
1    0    1    1

Desired Table:

      0   1   5
col1  1   2   0
col2  1   2   0
col3  2   1   0
col4  0   2   1

What is the best way to do this in Python?

Shubham Sharma :

You can try Series.value_counts:

df.apply(pd.Series.value_counts).fillna(0).astype(int).T

      0  1  5
col1  1  2  0
col2  1  2  0
col3  2  1  0
col4  0  2  1

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I count specific values across multiple columns in pandas

Pandas Pivot - Swap 'columns' and 'values'

Transpose or Pivot multiple columns in Pandas

pandas - remove duplicates, count items, from columns with multiple values

Pandas: Multiple columns containing Names and Values of Variables: How to use Pivot?

Count Boolean values from Pivot table with pandas

Python PANDAS: pivot_table count for multiple columns on same level?

Pandas, Pivot table from 2 columns with values being a count of one of those columns

How to pivot a pandas dataframe such that unique values across multiple columns become new columns?

pivot table in pandas with multiple columns

How to count values in rows across multiple columns with Pandas?

Group by multiple columns and pivot and count values from other column in pandas

Pandas Pivot Multiple Date Columns

Pivot values from multiple columns

Count the number of specific values in multiple columns pandas

PIVOT values from two columns to multiple columns

Excel pivot: count of items across multiple columns

Pandas pivot/merge multiple columns into single, using column headers as values

pandas: count values from multiple columns

Python, Pandas - count values based on multiple criteria in row and multiple columns

pivot longer with multiple columns and values

Pivot a pandas dataframe with multiple columns

Pivot table in pandas to count unique values

pandas dataframe group by multiple columns and count distinct values

pandas - split column with arrays into multiple columns and count values

pivot pandas dataframe and count true and false values

Groupby and count columns with multiple values

Count columns with multiple values

Count values for multiple columns