我对 Python 还很陌生。
我有以下示例数据框 df
。
Col1 Col2 Col3
0 0 1 1
1 1 1 0
2 0 1 1
3 1 0 1
4 0 0 1
如果我使用此代码df.apply(pd.Series.value_counts, axis=0)
我得到的结果是:
Col1 Col2 Col3
0 3 2 1
1 2 3 4
但是,我想要如下结果(如数据透视):
Col_Name 0 1
0 Col1 3 2
1 Col2 2 3
2 Col3 1 4
请提出建议。提前致谢。
最佳答案
将转置添加到您的解决方案 T
对于索引 rename_axis
中的新列与 reset_index
:
df1 = df.apply(pd.Series.value_counts, axis=0)
df1 = df1.T.rename_axis('Col_Name').reset_index()
print (df1)
Col_Name 0 1
0 Col1 3 2
1 Col2 2 3
2 Col3 1 4
另一种解决方案:
首先通过 stack
reshape 列或melt
,使用SeriesGroupBy.value_counts
最后通过 unstack
reshape 回来:
df = df.stack().groupby(level=1).value_counts().unstack()
print (df)
0 1
Col1 3 2
Col2 2 3
Col3 1 4
对于新列:
df = (df.stack()
.groupby(level=1)
.value_counts()
.unstack()
.rename_axis('Col_Name')
.reset_index())
print (df)
Col_Name 0 1
0 Col1 3 2
1 Col2 2 3
2 Col3 1 4
另一个解决方案:
df = (df.melt(var_name='Col_Name')
.groupby('Col_Name')['value']
.value_counts()
.unstack()
.rename_axis(None, axis=1)
.reset_index()
)
print (df)
Col_Name 0 1
0 Col1 3 2
1 Col2 2 3
2 Col3 1 4
关于python - 按列计算 pandas Dataframe 中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53353929/