Excel Python while循环不会执行

2024-03-29 14:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在这里测试时,它工作得非常好

import openpyxl, pprint
from openpyxl import load_workbook
import pandas as pd
import numpy as np
import os

df = pd.DataFrame(np.random.randn(15, 12), columns=list('ABCDEFGHIJKL'))
writer = pd.ExcelWriter('test_1.xlsx', engine='openpyxl')
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.close()

wb = load_workbook('test_1.xlsx')
sheet1 = wb['Sheet1']
my_list = []
for j in range(2, 8):
    my_list.append(sheet1.cell(row = 7, column = j).value)

def Standardized_C3():
        """=(AR2-MIN(AR$2:AR$17))/(MAX(AR$2:AR$17)-MIN(AR$2:AR$17))"""
        ar = 2
        while ar < sheet1.max_row:
            for rowNum in range(2, sheet1.max_row + 1):  # skip the first row
                sheet1.cell(row=rowNum, column=46).value = ('=IFERROR((AR' + str(ar) + '-MIN(AR$2:AR$' + str(sheet1.max_row) + '))/(MAX(AR$2:AR$' + str(sheet1.max_row) + 
                                                            ')-MIN(AR$2:AR$' + str(sheet1.max_row) + ')),"null")')
                ar+= 1
    Standardized_C3()

但是,当我在一个大数据集中使用完全相同的循环时,它似乎永远在继续。我不明白我让循环持续了10多分钟。你知道吗

def Standardized_C3():
    """=(AR2-MIN(AR$2:AR$15100))/(MAX(AR$2:AR$15100)-MIN(AR$2:AR$15100))"""
    ar = 2
    while ar < sheet1.max_row:
        for rowNum in range(2, sheet1.max_row + 1):  # skip the first row
            sheet1.cell(row=rowNum, column=46).value = ('=IFERROR((AR' + str(ar) + '-MIN(AR$2:AR$' + str(sheet1.max_row) + '))/(MAX(AR$2:AR$' + str(sheet1.max_row) + 
                                                        ')-MIN(AR$2:AR$' + str(sheet1.max_row) + ')),"null")')
            ar+= 1
Standardized_C3()

发现错误: str(sheet1.max_row)永远继续需要x = sheet1.max_row然后将str(x)添加到公式中


Tags: importminmaxlistrowpdarsheet1
1条回答
网友
1楼 · 发布于 2024-03-29 14:26:23

尝试使用打印进行调试

例如:

def Standardized_C3():
    """=(AR2-MIN(AR$2:AR$15100))/(MAX(AR$2:AR$15100)-MIN(AR$2:AR$15100))"""
    for rowNum in range(2, sheet1.max_row + 1):  # skip the first row
        print(rowNum)
        sheet1.cell(row=rowNum, column=46).value = ('=IFERROR((AR' + str(ar) + '-MIN(AR$2:AR$' + str(sheet1.max_row) + '))/(MAX(AR$2:AR$' + str(sheet1.max_row) + 
                                                    ')-MIN(AR$2:AR$' + str(sheet1.max_row) + ')),"null")')
Standardized_C3() 

看看脚本“冻结”在哪里

相关问题 更多 >