【问题标题】:Nested for loop to perform calculation on excel rows嵌套for循环以对excel行执行计算
【发布时间】:2021-06-04 10:34:42
【问题描述】:

我目前创建了以下代码以进入 Excel 工作表,并根据 Excel 工作表中的两列和我的代码中的两个变量创建两个新列。

现在我希望能够遍历包含这两个变量的元组列表,并在 Excel 工作表中创建多个新列。所以 waypointLat 和 waypointLon 将在一个像 ((51.454, -2.123), (51.555,-2.377), .....)这样的元组中

我真的有两个问题 1/ 这是最好的方法吗?我应该将数据加载为数据框吗? 2/ 如果在excel文件中可行,我如何遍历列?

谢谢,

waypointLat = '51.364718'
waypointLong = '-0.2507693'

wb = openpyxl.load_workbook(r'Desktop\Python Projects\Work - Transport Movement\CurrentYodelTransportLocations.xlsx')
ws1 = wb.active

last_row = 2200  # Enter last row of excel workbook here


for i in range(2, last_row):
    cell = "V" + str(i)
    cell2 = "W" + str(i)
    latitude = "N" + str(i)
    longitude = "O" + str(i)
    ws1[cell] = '=(((ACOS(SIN((' + latitude + '*PI()/180)) * SIN((' + waypointLat + '*PI()/180))+COS((' + latitude + '*PI()/180)) * COS((' + waypointLat + '*PI()/180)) * COS(((' + longitude + ' - ' + waypointLong + ')*PI()/180))))*180/PI())*60*1.1515*1.609344)'
    ws1[cell2] = '=IF(' + cell +'<=8,"Yes","No")'
wb.save(r'Desktop\Python Projects\Work - Transport Movement\CurrentYodelTransportLocationsAmended.xlsx')

【问题讨论】:

  • 我建议将文件加载到数据框中,对其执行操作,然后再次将其保存为 excel。

标签: python excel for-loop


【解决方案1】:

对于第二个问题,openpyxl 允许通过某些方式循环列,例如下面的代码:

for col in ws1.iter_cols(min_row=2, max_row=last_row, min_col=14, max_col=17):
    for cell in col:
        print(cell.value) # Otherwise you can set value

但是,出于您的目的,我想我们应该遍历行以便逐行处理数据:

for row in ws1.iter_rows(min_row=2, max_row=last_row, min_col=14, max_col=17):
    for cell in row:
        # manipulating data here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 2018-05-28
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多