Search code examples
pythonpython-3.xpyqt5qtablewidgetqtablewidgetitem

How can I sum up of all prices from tablewidget in python in terms of date column?


I have problem with to do code to sum up prices in terms of date column.

For example:

Photo of the tablewidget

31-12-2019

There we have :

39,0 and 62.0

I want sum up it and get 101.0 in other column or under last date in new row

All data in tablewidget i have thanks for excel spreedsheet reader procedure:

df = pd.read_excel('test_cod.xlsx')
self.tableWidget_25.setRowCount(len(df.index))
for i in range(len(df.index)):
    for j in range (len(df.columns)):

self.tableWidget_25.setItem(i,j,QTableWidgetItem(str(df.iat[i,j])))

test_cos.xlsx here: spreedsheet


Solution

  • I created a simple csv for this purpose, but you can easily apply this to your dataframe. The dataframe I used is this:

             Date  value  total
    0  24-11-2019     10    NaN
    1  24-11-2019     20    NaN
    2  24-11-2019     50    NaN
    3  26-11-2019     14    NaN
    4  26-11-2019     23    NaN
    5  02-12-2019     15    NaN
    6  02-12-2019     15    NaN
    

    This is the solution I came up with. It might not be most optimal, as I have barely ever used pandas, but it works. It doesn't loop within a loop which I think your draft is doing, which is better in terms of performance.

    import pandas as pd
    
    df = pd.read_csv('test.csv')
    
    compareVal = df.Date[0]
    
    total=0
    
    print(df)
    
    for x, date in enumerate(df.Date):
        if compareVal==date:
            total += df.value[x]
    
        else:
            df.at[x-1,'total'] = total
            total = df.value[x]
            compareVal = df.Date[x]
    
        if x == len(df)-1:
            df.at[x,'total'] = total
    
    print(df)
    
    

    This is the output:

             Date  value  total
    0  24-11-2019     10    NaN
    1  24-11-2019     20    NaN
    2  24-11-2019     50   80.0
    3  26-11-2019     14    NaN
    4  26-11-2019     23   37.0
    5  02-12-2019     15    NaN
    6  02-12-2019     15   30.0