Fastest way to populate QTableView from Pandas data frame

后端 未结 7 1208
面向向阳花
面向向阳花 2020-11-27 16:54

I\'m very new to PyQt and I am struggling to populate a QTableView control.

My code is the following:

def data_frame_to_ui(self, data_frame):
                


        
相关标签:
7条回答
  • 2020-11-27 17:34

    I've found all of the proposed answers painfully slow for DataFrames with 1000+ rows. What works for me blazingly fast:

    class PandasModel(QtCore.QAbstractTableModel):
        """
        Class to populate a table view with a pandas dataframe
        """
        def __init__(self, data, parent=None):
            QtCore.QAbstractTableModel.__init__(self, parent)
            self._data = data
    
        def rowCount(self, parent=None):
            return self._data.shape[0]
    
        def columnCount(self, parent=None):
            return self._data.shape[1]
    
        def data(self, index, role=QtCore.Qt.DisplayRole):
            if index.isValid():
                if role == QtCore.Qt.DisplayRole:
                    return str(self._data.iloc[index.row(), index.column()])
            return None
    
        def headerData(self, col, orientation, role):
            if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
                return self._data.columns[col]
            return None
    
    0 讨论(0)
提交回复
热议问题