该代码是在 Seaborn 中使用泰坦尼克号数据集构建 pd.crosstab。输出表中的列总和看起来很困惑。
import pandas as pd
import seaborn as sns
titanic = sns.load_dataset('titanic')
bin = [0,15,100]
titanic["adult"] = pd.cut(titanic.age, bin, labels=["kid","adult"])
pd.crosstab(titanic.survived, titanic.adult, normalize=True, margins=True)
我预计会有 0.116246/0.883754/1.000000
,但它在应放置列总和的最后一行给出 0.883754/0.116246/1.000000
。
最佳答案
总数的翻转/逆转仅仅是由于原始 age
列中以及随后您创建的分箱 adult
列中存在 NaN 值。您只需将 dropna=False
添加到 pd.crosstab()
命令中,这将返回正确的结果:
pd.crosstab(titanic.survived, titanic.adult, dropna=False, normalize=True, margins=True)
adult kid adult All
survived
0 0.047619 0.546218 0.616162
1 0.068627 0.337535 0.383838
All 0.116246 0.883754 1.000000
关于python - pandas 交叉表中的列困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55565324/