在for循环下使用try和except运行脚本

2024-05-18 09:40:10 发布

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

需要在for循环下使用try和except条件执行脚本,将数据帧分为两部分,并尝试执行第一部分,最后使用python追加回数据帧和concat

循环中的脚本正在执行,但最后它给出了错误

代码:

df = pd.read_excel(open(r'data.xlsx', 'rb'), sheet_name='sheet1')

df1 = df.loc[df['flag'] != 'Not feasible'] 
df = df.loc[df['flag'] == 'Not feasible'].copy()

for index, file in df..iterrows():
   # Run your cleaning codes   
   try:
      file['Joining_Date'][index] = pd.to_datetime(file['Joining_Date'], errors='coerce')
      file['Joining_Date'][index] = file['Joining_Date'].dt.strftime('%Y-%m-%d')
   except ValueError:
      file['status'] = ValueError
   try:
      file['age'][index] = file['age'].replace('[^\d.]', '', regex=True).astype(float)
   except ValueError:
      file['status'] = ValueError

   try:
      file[['col4','col5']][index] = file[['col4','col5']].apply(lambda x: x.astype(str).str.replace('\W',''))
   except ValueError:
      file['status'] = ValueError

   try:
      file['Contact'][index] = file['Contact'].replace('[^\d.]', '', regex=True).astype(float)
   except ValueError:
      file['status'] = ValueError

   file['flag'][index] = "feasible"

##Appending the values to dataframe and concat with the Non Executed data

df = df.apply(file, axis=1)

df = pd.concat([df, df1]).sort_index() 

获取错误:尝试使用时

df = df.apply(file, axis=1)

df = pd.concat([df, df1]).sort_index() 

错误:类型错误:'<;'“int”和“str”实例之间不支持此选项。

需要建议如何处理上述脚本


Tags: 脚本dfdateindexstatus错误fileflag