簡體   English   中英

Pandas pivot_table 因列和邊距而失敗

[英]Pandas pivot_table fails with columns and margin

使用 pandas 的 pivot_table 時出現 KeyError KeyError: "... not in index" 這是示例代碼:

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)

KeyError Traceback(最近一次調用最后一次)
...
KeyError:“['first''second'] 不在索引中”

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

正如 Asish 提到的,在調用.pivot_table之前執行reset_index()將完成這項工作。

該問題在 pandas GitHub 問題中提出,您可以在此處關注所有更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM