在使用pandas时,由于隔行读取删除了部分数据,导致删除数据后的索引不连续:
原数据:
删除部分数据后:
在绑定pyqt的tableview时需进行格式化,结果出现报错:
主要原因是索引值不连续,所以无法格式化,需对删除数据后的数据集进行重新索引,在格式化数据集之前加一句代码:
new_biao = biao.reset_index(drop=True)
顺利通过了编码并显示到tableview,问题解决。
附件:网上查到的格式化用的编码:
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 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, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self._data.columns[col]
return None
使用:
model = PandasModel(your_pandas_data_frame)
your_tableview.setModel(model)