Pandas:数据帧错误 - 2 列通过,传递的数据有 3 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43707296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:31:00  来源:igfitidea点击:

Pandas: DataFrame Error - 2 columns passed, passed data had 3 columns

pythonpython-3.xpandasnumpydataframe

提问by alexis

I want to initializes a dataframe and set its column and index as shown below but I face some issues while do like this:

我想初始化一个数据框并设置它的列和索引,如下所示,但是我在这样做时遇到了一些问题:

pd1 = pd.DataFrame(Matrix, columns=da, index=cl)

From above Matrix define as:

从上面的矩阵定义为:

Matrix = [[[0], [0], [0]],
          [[0], [0], [0]]]

and da as:

和 da 为:

da = ['A','B']

and cl as:

并分类为:

cl = ['X','Y','Z']

following error is occur while executing this line:

执行此行时发生以下错误:

# caller's responsibility to check for this..
raise AssertionError('%d columns passed, passed data had %s '
                     'columns' % (len(columns), len(content)))
# provide soft conversion of object dtypes

AssertionError: 2 columns passed, passed data had 3 columns

how to resolve this problem in python dataframe?

如何解决python数据帧中的这个问题?

回答by alexis

Make a dataframe without indices and you'll discover that pandasinterprets your matrix row-wise:

制作一个没有索引的数据框,你会发现它按pandas行解释你的矩阵:

>>> df = pd.DataFrame(Matrix)
>>> df
     0    1    2
0  [0]  [0]  [0]
1  [0]  [0]  [0]

So you need to transpose your data (or swap the columnsand indexarguments). This does the job:

所以你需要转置你的数据(或交换columnsindex参数)。这可以完成以下工作:

>>> df = pd.DataFrame(Matrix, index=da, columns=cl).transpose()
>>> df
     A    B
X  [0]  [0]
Y  [0]  [0]
Z  [0]  [0]

PS. I wonder if you really want the brackets around each value. But maybe you have a reason...

附注。我想知道您是否真的想要每个值周围的括号。但也许你有一个理由......