Ask Your Question
3

How can I display a string value as an integer on PandasTableModel using Python?

asked 2023-05-28 12:12:35 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-28 12:28:02 +0000

bukephalos gravatar image

You can convert the string value to an integer by using the astype method of the Pandas DataFrame. Here's an example:

import pandas as pd
from PyQt5.QtCore import QAbstractTableModel, Qt

class PandasTableModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole:
            value = self._data.iloc[index.row(), index.column()]
            if isinstance(value, str):
                return int(value)  # here we convert the string value to an integer
            return value

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

    def columnCount(self, parent):
        return len(self._data.columns)

    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole:
            return None
        if orientation == Qt.Horizontal:
            return self._data.columns[section]
        else:
            return str(section)

In this example, we check if the value is a string using the isinstance method. If the value is a string, we convert it to an integer using the int function before returning it. Otherwise, we return the original value. This should allow you to display string values as integers in your PandasTableModel.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-28 12:12:35 +0000

Seen: 10 times

Last updated: May 28 '23