我想初始化一个数据框并设置其列和索引,如下所示,但我在这样做时遇到一些问题:
pd1 = pd.DataFrame(Matrix, columns=da, index=cl)
从上面的矩阵定义为:
Matrix = [[[0], [0], [0]],
[[0], [0], [0]]]
和da为:
da = ['A','B']
和类别:
cl = ['X','Y','Z']
执行此行时出现以下错误:
# 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
如何在 python 数据框中解决这个问题?
最佳答案
制作一个没有索引的数据框,您会发现pandas
按行解释您的矩阵:
>>> df = pd.DataFrame(Matrix)
>>> df
0 1 2
0 [0] [0] [0]
1 [0] [0] [0]
因此您需要转置数据(或交换列
和索引
参数)。这可以完成工作:
>>> df = pd.DataFrame(Matrix, index=da, columns=cl).transpose()
>>> df
A B
X [0] [0]
Y [0] [0]
Z [0] [0]
PS。我想知道您是否真的想要每个值都加上括号。但也许你有一个理由......
关于python - Pandas:数据帧错误 - 传递了 2 列,传递的数据有 3 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43707296/