Display dataframe in QTableView

I am trying to load data from a file to a pandas dataframe and display it in a table.
The following example from the book (page 322) works as printed but not if I load data from a csv file.

File with numeric data:
2456196.58675383,1.0,0.0249552,1.1674299,0.9980308
2456196.59068867,1.0101816,0.0249541,1.1640897,0.9980369
2456196.59463292,1.0456737,0.0249531,1.1614767,0.9980417
2456196.59578575,1.00174,0.0249529,1.1608428,0.9980428
2456196.59815738,1.0148509,0.0249525,1.1597346,0.9980448

error message:
Traceback (most recent call last):
File “/home/rpi5/py-project/de.alu.eclipse.mep/b.py”, line 13, in data
return self._data[index.row()][index.column()]
~~~~~~~~~~^^^^^^^^^^^^^
File “/home/rpi5/venv/lib/python3.11/site-packages/pandas/core/frame.py”, line 4102, in getitem
indexer = self.columns.get_loc(key)
^^^^^^^^^^^^^^^^^^^^^^^^^
File “/home/rpi5/venv/lib/python3.11/site-packages/pandas/core/indexes/base.py”, line 3812, in get_loc
raise KeyError(key) from err
KeyError: 5

#listing 125 tableview_demo.py
import sys
import pandas as pd
from PyQt6.QtWidgets import QTableView, QMainWindow, QApplication
from PyQt6.QtCore import Qt, QAbstractTableModel

class TableModel(QAbstractTableModel):
def init(self, data):
super().init()
self._data = data

def data(self, index, role):
    if role == Qt.ItemDataRole.DisplayRole:
        return self._data[index.row()][index.column()]

def rowCount(self, index):
    return len(self._data)

def columnCount(self, index):
    return len(self._data[0])

class MainWindow(QMainWindow):
def init(self):
super().init()
self.table = QTableView()

    file = "/home/rpi5/Downloads/AAVSO_1.txt"
    tableHeader = ['DATE','DIFF','ERR','DETREND_1','DETREND_2']

    data = pd.read_csv(file,header=None)
    #data = [
        #[4, 1, 3, 3, 7],
        #[9, 1, 5, 3, 8],
        #[2, 1, 5, 3, 9],
        #]
    print(data)
    
    self.model = TableModel(data)
    self.table.setModel(self.model)
    
    self.setCentralWidget(self.table)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

Ok, I found die answer 20 pages later.
Sorry for my impatience.

1 Like