gpt4 book ai didi

python - pandas.crosstab 中缺少数据

转载 作者:太空狗 更新时间:2023-10-29 20:56:31 24 4
gpt4 key购买 nike

我正在用 pandas 制作一些交叉表:

a = np.array(['foo', 'foo', 'foo', 'bar', 'bar', 'foo', 'foo'], dtype=object)
b = np.array(['one', 'one', 'two', 'one', 'two', 'two', 'two'], dtype=object)
c = np.array(['dull', 'dull', 'dull', 'dull', 'dull', 'shiny', 'shiny'], dtype=object)

pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])

b one two
c dull dull shiny
a
bar 1 1 0
foo 2 1 2

但我真正想要的是:

b     one        two       
c dull shiny dull shiny
a
bar 1 0 1 0
foo 2 0 1 2

我通过添加新列并将级别设置为新的 MultiIndex 找到了解决方法,但这似乎很难...

有没有办法将 MultiIndex 传递给交叉表函数以预定义输出列?

最佳答案

交叉表函数有一个名为 dropna 的参数,默认设置为 True。此参数定义是否应显示空列(例如 one-shiny 列)。

我试过这样调用函数:

pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'], dropna = False)

这就是我得到的:

b     one          two       
c dull shiny dull shiny
a
bar 1 0 1 0
foo 2 0 1 2

希望这仍然对您有所帮助。

关于python - pandas.crosstab 中缺少数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com