Skip to content Skip to sidebar Skip to footer

How Can I Retrieve Data From A Qtablewidget To Dataframe?

I have a QTableWidget in editable mode in which user puts in integer input , how can I generate a list of data entered in this table so as to perform operations on it , here is my

Solution 1:

I think you're overcomplicating it a little with the updates/joins. The simplest approach is to create the full-size DataFrame first (filled with NaN) and then assign the data to this:

def dataframe_generation_from_table(self,table):
    number_of_rows = table.rowCount()
    number_of_columns = table.columnCount()

    tmp_df = pd.DataFrame( 
                columns=['Date', str(self.final_lvl_of_analysis), 'Value'], # Fill columnets
                index=range(number_of_rows) # Fill rows
                ) 

    for i in range(number_of_rows):
        for j in range(number_of_columns):
            tmp_df.ix[i, j] = table.item(i, j).data()

    return tmp_df

The above code assigns data to it's location by the numerical index, so position 1,1 in the QtTableWidget will end up at 1,1 in the DataFrame. This way you don't need to worry about the column headers when moving data. If you want to change the column names you can do that when creating the DataFrame, changing the values passed into the columns= parameter.

If you want to change a column to DateTime format, you should be able to do this in a single operation after the loop with:

tmp_df['Date'] = pd.to_datetime( tmp_df['Date'] )

Solution 2:

The change from .data() to .text() eliminated the ValueError.

def saveFile(self):
    df = pd.DataFrame()
    savePath = QtGui.QFileDialog.getSaveFileName(None, "Blood Hound", 
        "Testing.csv", "CSV files (*.csv)")        
    rows = self.tableWidget.rowCount()
    columns = self.tableWidget.columnCount()        

    for i in range(rows):            
        for j in range(columns):                
            df.loc[i, j] = str(self.tableWidget.item(i, j).text())              
    df.to_csv((savePath), header = None, index = 0)

Post a Comment for "How Can I Retrieve Data From A Qtablewidget To Dataframe?"