值错误:无法将形状(857,3)的输入数组广播为形状(857)

时间:2017-02-27 11:09:40

标签: python arrays numpy matplotlib

我一直试图将我从文本文件解析的数据库绘制成一个numpy数组。该数组有857行。

此错误不断出现,我不明白这意味着什么。

import matplotlib
import matplotlib.pyplot as plt
import numpy

def parseFile(file):
    F = open(file)
    n = len(F.readlines())  #no. of lines in file
    numpyMat = numpy.zeros((n,3)) # create numpy matrix
    classLabelVector = []
    F = open(file)          # from the beginning again
    i = 0
    for line in F.readlines():
        line = line.strip()
        listFromLine = line.split()
        numpyMat[i,:] = listFromLine[0:3]   # 3 is the no. of variables/columns
        classLabelVector.append(int(listFromLine[-1]))
    i+=1
    return numpyMat, classLabelVector

dataMatrix = parseFile('kiwibubbles_tran.txt')

fig = plt.figure()

ax = fig.add_subplot(111)
ax.scatter(dataMatrix[:1], dataMatrix[:2])   # Error

plt.show()

错误:ValueError:无法将形状(857,3)的输入数组广播为形状(857)

1 个答案:

答案 0 :(得分:0)

您的dataMatrix是一个元组,因此您有两个选择:

在两个不同的变量中获取功能结果

numpyMat, classLabels = parseFile('kiwibubbles_tran.txt')
fig = plt.figure()

ax = fig.add_subplot(111)
ax.scatter(numpyMat[:,1], numpyMat[:,2])

plt.show()

仅绘制元组中的numpyMat

dataMatrix = parseFile('kiwibubbles_tran.txt')
fig = plt.figure()

ax = fig.add_subplot(111)
ax.scatter(dataMatrix[0][:,1], dataMatrix[0][:,2])

plt.show()