Как обновить Qtableview, заполненный pandas фреймом данных, когда данные фрейма меняются? - PullRequest
0 голосов
/ 09 февраля 2020

У меня есть этот фрагмент кода для поиска текста в кадре данных, который является источником данных для Qtableview, я хочу вычесть результаты поиска и снова отобразить его в Qtableview

def searchForSymbol(self):
    searchForText = self.textEdit.toPlainText()
    self.listWidget.clear()
    self.searchResult = self.symbolListDF[self.symbolListDF["symbol"].str.cat(self.symbolListDF["symbolPersianShortName"], '***').str.contains(searchForText)]
    if self.dfPrediction is not None:
        self.find(searchForText)
        self.searchPredictionResult = self.dfPrediction[
            self.dfPrediction["symbol"].str.cat(self.dfPrediction["symbolPersianShortName"], '***').str.contains(
                searchForText)]
        self.fillPredictionTable(self.searchPredictionResult)


def showPredictionData(self):
     query = """SELECT symbol_1.symbol, symbol_1.symbolPersianShortName, prediction.date, prediction.prediction_5, prediction.prediction_4, prediction.prediction_3, prediction.prediction_2, prediction.prediction_1, prediction.prediction0, prediction.prediction1, prediction.prediction2, prediction.prediction3, prediction.prediction4, prediction.prediction5 FROM (SELECT symbol, symbolPersianShortName, symbolid FROM symboltable) as symbol_1 INNER JOIN prediction ON prediction.symbolid = symbol_1.symbolid ORDER BY prediction.date desc"""
        self.dfPrediction = pd.read_sql(query, sqlbase.engine)
        self.dfPrediction['date'] = pd.to_datetime(self.dfPrediction['date'],unit='s').apply(lambda x: x.date())
        self.fillPredictionTable(self.dfPrediction)



def fillPredictionTable(self, resultDf):
    self.predictionModel = PredictionModel(resultDf)

    if self.predictionTable is None:
        self.predictionTable = QtWidgets.QTableView(self.centralwidget)
        self.predictionTable.setObjectName("predictionTable")
        self.horizontalLayout_9.addWidget(self.predictionTable)
        self.predictionTable.setModel(self.predictionModel)
    else:
        self.predictionTable.setModel(self.predictionModel)

Код инициализации ( showPredictionData) работает нормально, но когда я пытаюсь использовать функцию searchForSymbol, она выдает эту ошибку:

(<class 'KeyError'>, KeyError(1,), <traceback object at 0x000002593B94C588>)

Более того, PredictionModel выглядит следующим образом:

class PredictionModel(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)
        self.dataChanged.emit(index, index)
        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()
...