python - Python DataFrame TypeError:只能将整数标量数组转换为标量索引
问题描述
我知道关于这个错误已经有几个问题了。但在这种特殊情况下,我不确定是否已经有解决我的问题的方法。我有这部分代码,我想打印 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,)
to ... 而不是xvec0
.
通过columns=feat_cols
应该可以解决问题:-)
推荐阅读
- macos - 为较旧的 Mac OS 版本构建 golang 应用程序的正确方法是什么?
- android - 华为定位包在室内无法获取到我的位置
- python - 该列表如何在 django 中返回值和键
- javascript - 在 Typescript 中使用外部 JS-Library(基本原语图)
- javascript - 如何使用 JavaScript 检查另一个元素中是否有一个元素
- java - 无法解析intellij中的符号jsonobject
- python - 图形大小随颜色条变化
- python - 在pygame中单击图像时如何运行函数?
- android-studio - 我不知道我的代码有什么问题
- kotlin - 发送不和谐心跳后客户端关闭连接,而不和谐响应 4002 错误代码