I have a data frame that looks like this .
I want to create a matrix where it counts the number of times each student says true and false.
How would I do this?
CodePudding user response:
df2 = df.melt()
pd.crosstab(df2['variable'], df2['value'])
Output:
value False True
variable
Student1 1 2
Student2 2 1
Student3 1 2
CodePudding user response:
You could stack
and unstack
with counting values in between:
out = df.stack().groupby(level=1).value_counts().unstack()
But an even simpler way is to simply count values:
out = df.sum().to_frame(name='T').assign(F=lambda x: len(df) - x)
Output:
False True
Student1 1 2
Student2 2 1
Student3 1 2
CodePudding user response:
You can do value_counts
df.apply(pd.Series.value_counts).T
Out[205]:
F T
St1 1 2
St2 2 1
St3 1 2
CodePudding user response:
You can use:
>>> df.melt().value_counts().unstack().rename_axis(index=None, columns=None)
False True
Student1 1 2
Student2 2 1
Student3 1 2