【问题标题】:How do you iterate over float excel columns in python?你如何迭代python中的浮动excel列?
【发布时间】:2022-01-13 10:39:09
【问题描述】:

假设我有一个如下所示的导入 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

我想以返回每列总和的方式遍历它,我该怎么做?

我试过这个:

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)

但我一直收到错误消息 TypeError: 'float' object is not iterable。 有谁知道如何解决这个问题?

【问题讨论】:

  • 你试过熊猫吗?

标签: python excel file


【解决方案1】:

我建议使用 Pandas 来执行此操作。以下代码使用read_excel 方法读取Excel 文件,并使用sum 数据框方法对每列求和。

import pandas as pd

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

column_sums = df.sum()

print(column_sums)

输出:

A    7.988534
B    1.303086
C    0.099099
D    5.276904
dtype: float64

注意:您需要安装 openpyxl 才能正常工作。否则你会遇到以下错误:ImportError: Missing optional dependency 'openpyxl'. Use pip or conda to install openpyxl.

【讨论】:

  • 我已经输入了这个,但它刚刚输出了列中的所有值。如果我输入 df.sum(1) 它只会给我两列的总数,而不是其他列
  • 我更新了答案以显示输出。如果您使用df.sum(axis=0),您将获得列内每个值的总和。如果你使用df.sum(axis=1),你会得到每行内元素的总和。
猜你喜欢
  • 1970-01-01
  • 2015-07-22
  • 2018-05-15
  • 1970-01-01
  • 2020-10-12
  • 2016-01-22
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多