如何解决pandas中多列的断言错误 [英] How to resolve Assertion Error for multiple columns in pandas
本文介绍了如何解决pandas中多列的断言错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Pandas文档提供了以下代码,效果很好:
Pandas documentation has given following code, which works fine:
frame = pd.DataFrame(np.arange(12).reshape((4, 3)),
index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
columns=[['Ohio', 'Ohio', 'Colorado'],
['Green', 'Red', 'Green']])
基于上述概念,我尝试了以下代码,但它不起作用:
I tried following code, based on above concept, but it does not work:
hi5 = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],
index = [['a','a','a','b'],[1,2,3,1]],
columns=[['Ohio', 'Ohio', 'Colorado'],
['Green', 'Red', 'Green']])
上面的代码给出以下错误:
It is giving Following error for above code:
AssertionError: 2 columns passed, passed data had 3 columns
推荐答案
我认为它更深入:
以下代码有效:
frame = pd.DataFrame(np.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]),
index=[['a', 'a', 'a', 'b'], [1, 2, 3, 1]],
columns=[['Ohio', 'Ohio', 'Colorado'],
['Green', 'Red', 'Green']])
下面的代码不起作用,唯一的区别是我们现在传递的是列表而不是数组:
The code below doesn't work, the only difference is we're now passing a list instead of an array:
frame = pd.DataFrame([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]],
index=[['a', 'a', 'a', 'b'], [1, 2, 3, 1]],
columns=[['Ohio', 'Ohio', 'Colorado'],
['Green', 'Red', 'Green']])
AssertionError: 2 columns passed, passed data had 3 columns
但是,如果我们将此代码分成多个步骤,它将再次起作用.
However, if we split this code up into steps, it works again.
frame = pd.DataFrame([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]])
frame.index=[['a', 'a', 'a', 'b'], [1, 2, 3, 1]]
frame.columns=[['Ohio', 'Ohio', 'Colorado'],
['Green', 'Red', 'Green']]
这篇关于如何解决pandas中多列的断言错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文