简体   繁体   English

如何迭代 python 中的浮动 excel 列?

[英]How do you iterate over float excel columns in python?

Say I have an imported excel sheet that looks like this:假设我有一张进口的 excel 表,如下所示:

    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 .但我不断收到错误TypeError: 'float' object is not iterable Does anyone know how to resolve this?有谁知道如何解决这个问题?

I recommend using Pandas to do this.我建议使用 Pandas 来执行此操作。 The following code reads in the Excel file using the read_excel method and the sums each column using the sum dataframe method.以下代码使用read_excel方法读取 Excel 文件,并使用sum dataframe 方法对每列求和。

import pandas as pd

df = pd.read_excel('test.xlsx')

column_sums = df.sum()

print(column_sums)

Output: 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.注意:您需要安装openpyxl才能正常工作。 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. ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM