Say I have an imported excel sheet that looks like this:
A B C D
4.296178, 0.434362, 0.033033, 2.758968
0.296178, 0.434362, 0.033033, 0.758968
3.396178, 0.434362, 0.033033, 1.758968
And I want to iterate through it in a way that returns the sum of each column, how would I do this?
I have tried this:
import openpyxl
templist = []
Col_one_total = []
Col_two_total = []
Col_three_total = []
for row in sheet.rows:
Col_one_total += row[0].value
Col_two_total += row[1].value
Col_three_total += row[2].value
templist.append(Col_one_total)
templist.append(Col_two_total)
templist.append(Col_three_total)
return max(templist)
but I keep getting an error saying TypeError: 'float' object is not iterable
. Does anyone know how to resolve this?
I recommend using Pandas to do this. The following code reads in the Excel file using the read_excel
method and the sums each column using the sum
dataframe method.
import pandas as pd
df = pd.read_excel('test.xlsx')
column_sums = df.sum()
print(column_sums)
Output:
A 7.988534
B 1.303086
C 0.099099
D 5.276904
dtype: float64
Note: You need to have openpyxl
installed for this to work. Else you'll run into the following error: ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl.
ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.