如何使用PyQt5显示Pandas数据帧

时间:2017-06-17 09:47:51

标签: python pandas pyqt pyqt5 qtableview

我对self.tableView.set??????????(df)下面的行有问题,该行应该在PyQt5中显示数据帧。我放 ???那里我错过了我需要的代码。

def btn_clk(self):
        path = self.lineEdit.text()
        df = pd.read_csv(path)
        self.tableView.set??????????(df)

其余代码有效,因为如果我在上面的代码中使用print(df),则数据框将在IPython控制台中打印出来。所以,Pandas读取CSV并打印出来。

但是,我尝试了很多东西让它在PyQt5中显示,但没有任何效果。我对PyQt不太熟悉,刚刚开始玩它而且我被困在这里。

这是我的代码:

from PyQt5 import QtCore, QtGui, QtWidgets
import pandas as pd
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(662, 512)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")
        self.verticalLayout.addWidget(self.lineEdit)
        self.tableView = QtWidgets.QTableView(self.centralwidget)
        self.tableView.setObjectName("tableView")
        self.verticalLayout.addWidget(self.tableView)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout.addWidget(self.pushButton)
        self.horizontalLayout.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 662, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))


        self.pushButton.clicked.connect(self.btn_clk)

        MainWindow.show()

    def btn_clk(self):
        path = self.lineEdit.text()
        df = pd.read_csv(path)
        self.tableView.set????????????(df)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

3 个答案:

答案 0 :(得分:30)

QTableView的情况下,数据必须通过模型提供,因为它实现了MVC模型 - 视图 - 控制器)范例,在大熊猫的情况下没有默认模型,但我们可以创建自定义,如以下部分所示:

class PandasModel(QtCore.QAbstractTableModel): 
    def __init__(self, df = pd.DataFrame(), parent=None): 
        QtCore.QAbstractTableModel.__init__(self, parent=parent)
        self._df = df

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            try:
                return self._df.columns.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()
        elif orientation == QtCore.Qt.Vertical:
            try:
                # return self.df.index.tolist()
                return self._df.index.tolist()[section]
            except (IndexError, ):
                return QtCore.QVariant()

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if not index.isValid():
            return QtCore.QVariant()

        return QtCore.QVariant(str(self._df.ix[index.row(), index.column()]))

    def setData(self, index, value, role):
        row = self._df.index[index.row()]
        col = self._df.columns[index.column()]
        if hasattr(value, 'toPyObject'):
            # PyQt4 gets a QVariant
            value = value.toPyObject()
        else:
            # PySide gets an unicode
            dtype = self._df[col].dtype
            if dtype != object:
                value = None if value == '' else dtype.type(value)
        self._df.set_value(row, col, value)
        return True

    def rowCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.index)

    def columnCount(self, parent=QtCore.QModelIndex()): 
        return len(self._df.columns)

    def sort(self, column, order):
        colname = self._df.columns.tolist()[column]
        self.layoutAboutToBeChanged.emit()
        self._df.sort_values(colname, ascending= order == QtCore.Qt.AscendingOrder, inplace=True)
        self._df.reset_index(inplace=True, drop=True)
        self.layoutChanged.emit()

然后使用它:

def btn_clk(self):
    path = self.lineEdit.text()
    df = pd.read_csv(path)
    model = PandasModel(df)
    self.tableView.setModel(model)

enter image description here

完整代码为here

答案 1 :(得分:0)

要修复排序...

from natsort import natsorted, index_natsorted, order_by_index
def sort(self, column, order):
    self.layoutAboutToBeChanged.emit()
    if order == 0:
        self._df = self._df.reindex(index=order_by_index(self._df.index, index_natsorted(eval('self._df.%s' % (list(self._df.columns)[column])))))
    else:
        self._df = self._df.reindex(index=order_by_index(self._df.index, reversed(index_natsorted(eval('self._df.%s' % (list(self._df.columns)[column]))))))

    self._df.reset_index(inplace=True, drop=True)
    self.setDataFrame(self._df)
    self.layoutChanged.emit()

答案 2 :(得分:0)

就像@DanielR 所说的,标记的答案不再有效,但 this tutorial 似乎有效。

pandas.version='1.0.1', PYQT_VERSION_STR = 5.11.3


class pandasModel(QAbstractTableModel):

    def __init__(self, data):
        QAbstractTableModel.__init__(self)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parnet=None):
        return self._data.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None