【问题标题】:Python issue with reading and calculating data from excel file从excel文件读取和计算数据的Python问题
【发布时间】:2017-05-24 01:07:39
【问题描述】:

I have attached a screenshot of the excel file I am working with 我正在尝试阅读这个包含所有州(B 列)、县(C 列)和人口(D 列)的 excel 文件。我想计算每个州的人口。

我知道我们都可以通过多种方式做到这一点,而且肯定有一种方法可以用更少的易于理解的代码行来做到这一点。我会很感激,但我也想知道如何按照我的想法执行此操作 - 首先找出唯一的状态名称,然后循环遍历工作表以按状态添加所有列。

这是我的代码:

x = wb.get_sheet_names()
sheet = wb.get_sheet_by_name('Population by Census Tract')
PopData = {}
StateData = []
i = 3
j = 0
k=""

#First value entered
StateData.append(sheet['B' + str(2)].value)

#Unique State Values calculated
for row in range(i, sheet.max_row + 1):
    if any(sheet['B' + str(row)].value in s for s in StateData):
        i=i+1
    else:
        StateData.append(sheet['B' + str(row)].value)
print(StateData)

#Each State's Population calculated
for s in StateData:
    for row in range(2, sheet.max_row + 1):
        if sheet['B' + str(row)].value == StateData[s]:
            j = j + sheet['D' + str(row)].value
    PopData[StateData[s]] = j 
print(PopData)

我收到此错误:

if sheet['B' + str(row)].value == StateData[s]:
TypeError: list indices must be integers or slices, not str

【问题讨论】:

  • 显然,sheet 是一个列表,而您将其视为字典。只有字典才能在“字符串”键中获取值。列表只能使用整数获取值!如果您至少发布部分 Excel 表格,我们可以为您提供更多帮助。
  • 感谢您抽出宝贵时间回答。我附上了我正在使用的 excel 文件的屏幕截图。
  • 您好,还要添加代码的import 部分,以帮助了解您正在使用哪些模块。

标签: excel python-3.x calculation


【解决方案1】:

如下:

for s in StateData:
    for row in range(2, sheet.max_row + 1):
        if sheet['B' + str(row)].value == StateData[s]:
            j = j + sheet['D' + str(row)].value
    PopData[StateData[s]] = j 

s 已经是StateData 列表的一个元素。你想做的大概是:

for s in StateData:
    for row in range(2, sheet.max_row + 1):
        if sheet['B' + str(row)].value == s:
            j = j + sheet['D' + str(row)].value
    PopData[StateData[s]] = j 

for i, s in enumerate(StateData):
    for row in range(2, sheet.max_row + 1):
        if sheet['B' + str(row)].value == StateData[i]:
            j = j + sheet['D' + str(row)].value
    PopData[StateData[s]] = j 

但第一种选择更优雅并且(也许)稍微快一些。

【讨论】:

  • 再次感谢您。第一个选项给了我同样的错误,但这次是在线“PopData[StateData[s]] = j”。所以我在下面使用了这段代码,它起作用了。 for i, s in enumerate(StateData): for row in range(2, sheet.max_row + 1): if sheet['B' + str(row)].value == s: j = j + sheet['D ' + str(row)].value PopData[StateData[i]] = j
猜你喜欢
  • 1970-01-01
  • 2015-06-04
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
  • 2019-02-21
相关资源
最近更新 更多