繁体   English   中英

Python DataFrame 类型错误:仅 integer 标量 ZA3CBC3F9D0CE2F2C1554E1B61 可以转换为标量索引C1B67

[英]Python DataFrame TypeError: only integer scalar arrays can be converted to a scalar index

我知道关于这个错误已经有几个问题了。 但在这种特殊情况下,我不确定是否已经有解决我的问题的方法。 我有这部分代码,我想打印 Dataframe df 的列“y”。 出现以下错误:TypeError: only integer scalar arrays can be convert to a scalar index

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

可以打印整个 DataFrame。 这看起来像:

        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 阵列有关。 先感谢您!

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

传递columns=feat_cols应该可以解决问题:-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM