我正在制作一些带有熊猫的交叉表:
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传递给交叉表函数来预定义输出列?
在Pandas中有没有机会通过MultiIndex对数据进行分组?通过这个我的意思是传递给groupby函数不仅键,而是键和值预定义数据帧列?
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', 'shiny', 'dull', 'dull', 'dull', 'shiny', 'shiny'], dtype=object)
df = pd.DataFrame([a, b, c]).T
df.columns = ['a', 'b', 'c']
df.groupby(['a', 'b', 'c']).apply(len)
a b c
bar one dull 1
two dull 1
foo one dull 1
shiny 1
two dull 1
shiny 2
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是以下内容:
mi = pd.MultiIndex(levels=[['foo', 'bar'], ['one', 'two'], ['dull', 'shiny']],
labels=[[0, 0, 0, 0, 1, 1, …Run Code Online (Sandbox Code Playgroud)