在while循环下迭代行,后跟数据帧的If-Else条件时出错

2024-06-17 14:48:44 发布

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

在当前任务中,我尝试迭代所有excel行,然后将每一行作为新记录复制到目标模板文件中。源文件和目标文件不同,因此我将值分配给目标单元格

# code run sample file
# import os
import pandas as pd
import xlwings as xw
newdir_path = " "
file1 = "list.xlsx"
# read the source file
data = pd.read_excel(file1, sheet_name=0, header=0,
                                 index_col=False, keep_default_na=True)
# creating pandas dataframe from the source file
df = pd.DataFrame(data, columns=['Funktion', 'AD65', 'W70', 'B14', 'AC21'])
B14 = ['RR', 'BB', 'RA', 'MM']
booleans = []
# to iterate all the rows
for i in df.itertuples(index=True):
    # only to read the rows where column AD65(2nd column) does not have blank value or none
    while i[AD65] != 'None':
      # to retrieve the row values
      # when B14 value is RR
      if B14 == 'RR':
         print(i)
         # retrieving the values
         Funktion = i.Funktion
         AD65 = i.AD65
         W70 = i.W70
         B14 = i.B14
         AC21 = i.AC21
         booleans.append(True)
         
      # when B14 is B1
      elif B14 == 'BB':
         print(i)
         Funktion = i.Funktion
         AD65 = i.AD65
         W70 = i.W70
         B14 = i.B14
         AC21 = i.AC21
         booleans.append(True)
      
      elif B14 == 'RA':
         # repeating the same as above
         booleans.append(True)
      
      elif B14 == 'MM':
         booleans.append(True)
      else:
    # I want to skip the rows when B14 value is blank

注意:我还使用if df.loc[['B14']=='RR']:尝试了我的条件,它抛出raise KeyError(键) KeyError:错误


Tags: thetoimporttrue目标asrrfile