Python PyQt显示tableview数据帧的垂直标头
我想知道如何在tableview中显示垂直标题。垂直标题应显示索引 我已经创建了一个股票价格的数据框架。日期是数据帧的索引(即2017-12-06),收盘价是数据帧的价值(即50美元) 我编写了一个使用QabStretctTableModel的模型类。 我的headerData方法如下:Python PyQt显示tableview数据帧的垂直标头,python,python-3.x,pandas,pyqt,pyqt5,Python,Python 3.x,Pandas,Pyqt,Pyqt5,我想知道如何在tableview中显示垂直标题。垂直标题应显示索引 我已经创建了一个股票价格的数据框架。日期是数据帧的索引(即2017-12-06),收盘价是数据帧的价值(即50美元) 我编写了一个使用QabStretctTableModel的模型类。 我的headerData方法如下: def headerData(self, rowcol, orientation, role): if orientation == QtCore.Qt.Horizontal and role == Q
def headerData(self, rowcol, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[rowcol]
if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return self._data.index[rowcol]
return None
但显示的tableview中没有索引
显示的TableView的屏幕截图
整个源代码如下所示:
from PyQt5 import QtCore
class PandasModel(QtCore.QAbstractTableModel):
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = data
def rowCount(self, parent=None):
return len(self._data.values)
def columnCount(self, parent=None):
return self._data.columns.size
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return str(self._data.values[index.row()][index.column()])
return None
def headerData(self, rowcol, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[rowcol]
if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return self._data.index[rowcol]
return None
我有你的密码
编辑:我的数据帧源代码附件
dates = pd.date_range(start_date, end_date)
df = pd.DataFrame(index=dates)
df_temp = pd.read_csv(directory, index_col='Date', parse_dates=True, usecols=['Date', 'Adj Close'],
na_values=['nan'])
df = df.join(df_temp)
df = df.dropna(axis=0, how='any')
return df
编辑2:
csv文件的屏幕截图
问题的原因是索引返回PyQt无法识别的数据类型,解决方案是将其转换为字符串,为此我们有两个可能的选项:使用
str()
或指示格式的方法:
def headerData(self, rowcol, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[rowcol]
if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
return self._data.index[rowcol].strftime('%Y-%m-%d') # or str(self._data.index[rowcol])
你可以展示你是如何形成数据框架的。嘿@eyllanesc我已经编辑了我的帖子:)你可以共享你的.csv文件添加了一个csv文件的屏幕截图。数据帧已成功创建。我只是不知道为什么垂直标题没有显示!你帮了我很多!问题解决了。这两种解决方案对我都有效!祝你有一个愉快的一天:)几乎要疯了,正在使用一些数据帧而不是其他数据帧,应用了你的东西,工作起来很有魅力