pandas.crosstab中缺少数据

时间:2013-06-08 19:24:50

标签: python 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传递给交叉表函数来预定义输出列?

2 个答案:

答案 0 :(得分:5)

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

我试着像这样调用这个函数:

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

希望这仍然有用。

答案 1 :(得分:4)

我认为没有办法做到这一点,并且crosstab在源代码中调用pivot_table,这似乎也不提供此功能。 我将其提升为问题here

一个hacky解决方法(可能与您已经使用的相同或不同......):

from itertools import product
ct = pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
a_x_b = list(product(np.unique(b), np.unique(c)))
a_x_b = pd.MultiIndex.from_tuples(a_x_b)

In [15]: ct.reindex_axis(a_x_b, axis=1).fillna(0)
Out[15]:
      one          two
     dull  shiny  dull  shiny
a
bar     1      0     1      0
foo     2      0     1      2

如果product太慢,则此处为a numpy implementation