我正在制作一些带有熊猫的交叉表:
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
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是以下内容:
b one two
c dull shiny dull shiny
a
bar 1 0 1 0
foo 2 0 1 2
Run Code Online (Sandbox Code Playgroud)
我通过添加新列和设置级别作为新的MultiIndex找到了解决方法,但似乎很难......
有没有办法将MultiIndex传递给交叉表函数来预定义输出列?