当前位置: 首页 > 知识库问答 >
问题:

Python DataFrame TypeError:只有整数标量数组可以转换为标量索引

顾穆冉
2023-03-14

我知道关于这个错误已经有几个问题了。但在这种特殊情况下,我不确定是否已经有了解决我问题的方法。我有这部分代码,我想打印数据帧df的“y”列。发生以下错误:TypeError:只有整数标量数组才能转换为标量索引

labels=[]
xvectors=[]

for i in data:
    labels.append(i[0])
    xvectors.append(i[1])

X = np.array(xvectors)
y = np.array(labels)

feat_cols = [ 'xvec'+str(i) for i in range(X.shape[1]) ]
print(feat_cols)
df = pd.DataFrame(X,columns=[feat_cols])
df['y']= y
#df['label'] = df['y'].apply(lambda i: str(i))
print(df['y'])

X, y = None, None

可以打印整个数据帧。这看起来像:

        xvec0     xvec1     xvec2     xvec3     xvec4  ...   xvec508   xvec509   xvec510   xvec511        y
0    3.397163 -1.112423  0.414708  0.563083  1.371336  ...  1.201095 -0.076261 -0.620443 -1.231465  DA01_03
1    0.159473  1.884818 -1.511547 -0.153500 -0.635701  ... -1.217205 -1.922081  0.878613  0.087912  DA01_06
2    1.089404  0.331919 -1.027480  0.594129 -2.473234  ... -3.505570 -3.509632 -0.553128 -0.453307  DA01_10
3    0.183993 -1.741467 -0.142570 -3.158320  4.355789  ...  3.857311  3.142393  0.991663 -2.842322  DA01_14

这是整个错误消息:

    print(df['y'])
  File "/usr/local/lib/python3.7/dist-packages/pandas/core/frame.py", line 2958, in __getitem__
    return self._get_item_cache(key)
  File "/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py", line 3270, in _get_item_cache
    values = self._data.get(item)
  File "/usr/local/lib/python3.7/dist-packages/pandas/core/internals/managers.py", line 960, in get
    return self.iget(loc)
  File "/usr/local/lib/python3.7/dist-packages/pandas/core/internals/managers.py", line 977, in iget
    block = self.blocks[self._blknos[i]]
TypeError: only integer scalar arrays can be converted to a scalar index

我认为这与numpy阵列有关。提前谢谢你!

共有1个答案

宇文俊风
2023-03-14

参数作为列表中的列表传递(feat_cols已经是列表类型)。这将使列标题变成二维:您可以看到df。info()说它的范围从(xvec0,)到。。。而不是xvec0

传递columns=feat\u cols应该可以做到:-)

 类似资料: