2 回答
TA贡献1796条经验 获得超4个赞
正如您所说,对所有列使用交叉表会按每列分解结果。您可以使用单独的交叉表,然后连接
pd.concat([pd.crosstab(df.Question1, df.Gender), pd.crosstab(df.Question1, df.Income), pd.crosstab(df.Question1, df.Age)], axis = 1)
F M 20-30k 30-40k 40k+ 20-30 30-45
Question1
Bad 2 1 1 1 1 2 1
Good 0 1 1 0 0 1 0
OK 2 0 0 0 2 1 1
编辑:在列中获得额外级别
age = pd.crosstab(df.Question1, df.Age)
age.columns = pd.MultiIndex.from_product([['Age'], age.columns])
gender = pd.crosstab(df.Question1, df.Gender)
gender.columns = pd.MultiIndex.from_product([['Gender'], gender.columns])
income = pd.crosstab(df.Question1, df.Income)
income.columns = pd.MultiIndex.from_product([['Income'], income.columns])
pd.concat([age, gender, income], axis = 1)
Age Gender Income
20-30 30-45 F M 20-30k 30-40k 40k+
Question1
Bad 2 1 2 1 1 1 1
Good 1 0 0 1 1 0 0
OK 1 1 2 0 0 0 2
添加回答
举报