因此,Im目前仅从ZeroMQ消息系统中获取有限的数据,并将其全部添加到Dataframe,然后使用从堆栈中的某人获取的代码将Dataframe转换为Pandas模型。然后通过PyQt5 Tableview运行该模型。
每次我运行tableview代码时,将Dataframe转换为Tableview模型后,内核就会死掉。我试图至少处理一个异常,但它甚至不会引发超一般的运行时错误。每次都死了......
出于测试目的,我使用了带有数据的CSV试图将其转换为可行的模型。由于没有硬编码格式,因此可以使用任何csv或数据进行测试。
from PyQt5 import QtCore, QtGui, QtWidgets
import pandas as pd
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 createview(title, model):
try:
view = QtWidgets.QTableView()
view.setWindowview
except:
raise RuntimeError("I know python!")
if __name__=="__main__":
df=pd.read_csv("C:\Excel Sheets\Test_CSV_6-18-18.csv")
model = PandasModel(df)
createview("Model", model)