IndexError:数组索引过多:数组是 0 维,但有 2 个索引

问题描述 投票:0回答:2

我想通过PyQt5引入一个文本文件并用数据值绘制一个图表。

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
from PyQt5.QtGui import QIcon
import numpy as np
import matplotlib.pyplot as plt

class MyApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.statusBar()

        openFile = QAction(QIcon('folder.png'), 'Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Text.txt')
        openFile.triggered.connect(self.show)

        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)

        self.setWindowTitle('File Dialog')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def show(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', './')

        if fname[0]:
            f = open(fname[0], 'r')


            with f:
                data = f.read()
                data2=np.array(data)
                x=data2[1:,0]
                y=data2[1:,1]

                plt.plot(x,y)
                plt.show()

 if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

enter image description here

文本文件照片。

这是出现的错误:

x=data2[1:,0]
IndexError: too many indices for array: array is 0-dimensional, but 2 were indexed
python numpy pyqt5 numpy-ndarray index-error
2个回答
0
投票

当您使用

numpy
时,您不需要编写自己的代码来从文件加载数据。使用
numpy
功能为您完成此操作。

show()
中,我建议像这样更改代码:

data = np.loadtxt(fname[0], skiprows=1)
x = data[:, 0]
y = data[:, 1]
plt.plot(x, y)
plt.show()

0
投票

另一个答案向您展示了如何正确执行此操作,因此我将解释您的代码中出了什么问题。

data = f.read()
中,文件存储为字符串而不是数组。如果你检查它,你会看到类似
x    y     \n1    2    \n
的东西,其中
\n
是换行符。因此,
data2 = np.array(data)
最终创建了一个包含单个字符串的 numpy 数组。

因为您的数组只有一个项目,所以它具有 0 维,而不是您期望的二维。

© www.soinside.com 2019 - 2024. All rights reserved.