gpt4 book ai didi

python - Pandas pivot_table 因列和边距而失败

转载 作者:行者123 更新时间:2023-12-03 17:22:58 25 4
gpt4 key购买 nike

我收到了 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)

KeyError Traceback (most recent call last)
...
KeyError: "['first' 'second'] not in index"


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

最佳答案

作为阿西什mentioned ,执行 reset_index()调用前 .pivot_table会做的工作。
这个问题是在pandas GitHub问题中提出的,可以关注所有更新here .

关于python - Pandas pivot_table 因列和边距而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65441897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com