Pandas pivot_table 因列和边距而失败

Dav*_*voz 5 python pivot-table pandas

我正在KeyError: "... not in index"使用 pandas 的 pivot_table一段时间。这是示例代码:

arrays = [['bar', 'bar', 'foo', 'foo'],
          ['one', 'two', 'one', 'two'], ['A','A','B','B']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second', 'third'])
values = np.array([[1,2,3,4],[5,6,7,8]])
df = pd.DataFrame(values.T, index=index, columns = ['0', '1'])

# here comes the pivot_table, this one works, it has 'colums'
df.pivot_table(index = ['first', 'second'],  columns = 'third', aggfunc = 'sum')

#this one works, it has 'margins'
df.pivot_table(index = ['first', 'second'],  aggfunc = 'sum', margins=True)

#this one fails, it has both 'columns' and 'margins'
df.pivot_table(index = ['first', 'second'],  columns = 'third', aggfunc = 'sum', margins=True)
Run Code Online (Sandbox Code Playgroud)

KeyError Traceback(最近一次调用最后一次)
...
KeyError: "['first' 'second'] not in index"

不知何故,列和边距不兼容。

Gon*_*ica 1

正如 Asish提到的reset_index(),在调用之前执行一次.pivot_table即可完成工作。

该问题是在 pandas GitHub Issues 中提出的,可以在此处关注所有更新。