DataFrame.apply有2个解决方案,用于按列应用功能,但索引按其交点对齐,因此添加了NaN :
df1 = df.apply(pd.value_counts)
print (df1)
PassengerId Survived Pclass
0 NaN 1.0 NaN
1 1.0 2.0 1.0
2 1.0 NaN NaN
3 1.0 NaN 2.0
df1 = df.apply(pd.Series.value_counts)
print (df1)
PassengerId Survived Pclass
0 NaN 1.0 NaN
1 1.0 2.0 1.0
2 1.0 NaN NaN
3 1.0 NaN 2.0
df1 = df.stack().groupby(level=1).value_counts().rename_axis(('a','b')).reset_index(name='c')
print (df1)
a b c
0 PassengerId 1 1
1 PassengerId 2 1
2 PassengerId 3 1
3 Pclass 3 2
4 Pclass 1 1
5 Survived 1 2
6 Survived 0 1
df1 = (df.apply(pd.Series.value_counts)
.stack()
.astype(int)
.rename_axis(('a','b'))
.reset_index(name='c')
print (df1)
a b c
0 0 Survived 1
1 1 PassengerId 1
2 1 Survived 2
3 1 Pclass 1
4 2 PassengerId 1
5 3 PassengerId 1
6 3 Pclass 2