在While循环中刷新Python中的数据帧

2024-06-17 12:45:57 发布

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

我有一个数据框,它从SQL中获取数据,并根据列的条件发送电子邮件。但是这些列在SQL中不存在,我需要在创建数据帧之后创建它们。这里的问题是我有一个while循环,它每10秒检查一次列的状态。我注意到while循环在所有条件下都能很好地工作,但是数据帧没有从SQL刷新,因为它在while循环之外。如果我将数据帧放在while循环中,last_email_sent被初始化为None受到影响并给出错误的输出。下面是我的伪代码,其中描述了逻辑。你知道吗

#initialisation and fetching of the table from SQL
df = pd.read_sql('SELECT * FROM stations', cnxn)
df['Timeflag'] = now - df['last_reported']
df['last_email_sent'] = None

while True:
   for index in df.index:
       if(df['Timeflag'] == 1 and df.loc[df.index[index], "Last_email_sent"] is None:
            print('pass')
            minutes = divmod((now - df.loc[index, "Last_email_sent"]).total_seconds(), 60)[0]

       elif df.loc[index, 'Time flag'] == 1 and minutes < min:
            print('fail')
            minutes = divmod((now - df.loc[index, "Last_email_sent"]).total_seconds(), 60)[0]
               else:
        print('false')
time.sleep(10)  

问题是我不能像下面这样做,因为在for循环中last_email_sent不能是None,并且必须保留while循环第一次迭代后流行的最后更新值。你知道吗

while True:
    #initialisation and fetching of the table from SQL
    df = pd.read_sql('SELECT * FROM stations', cnxn)
    df['Timeflag'] = now - df['last_reported']
    df['last_email_sent'] = None

是否有其他方法调用for循环中的数据帧,从而同时计算其他列?你知道吗


Tags: and数据nonedfforsqlindexemail
1条回答
网友
1楼 · 发布于 2024-06-17 12:45:57

如果我没有用正确的方法重新编写您的问题,您可以执行以下操作,但是请注意,它还没有准备好使用代码,我只想演示逻辑

First_Start = True  # first time we define db colum to None
Last_Email_Sent = None  # when we sent the last email

while True:

    # read data from db heare and do what you need
    df = pd.read_sql('SELECT * FROM stations', cnxn)
    df['Timeflag'] = now - df['last_reported']
    if First_Start:
        df['last_email_sent'] = None
        First_Start = False  # never again will be True
    else:
        df['last_email_sent'] = Last_Email_Sent

    while True:
       for index in df.index:  # cheack all you want in df
           if(df['Timeflag'] == 1 and df.loc[df.index[index], "Last_email_sent"] is None:
                print('pass')
                minutes = divmod((now - df.loc[index, "Last_email_sent"]).total_seconds(), 60)[0]

           elif df.loc[index, 'Time flag'] == 1 and minutes < min:
                print('fail')
                minutes = divmod((now - df.loc[index, "Last_email_sent"]).total_seconds(), 60)[0]
            else:
                print('false')

        Last_Email_Sent  = ??? # define new value here!
        break # all work is done and you go out of the while loop
    time.sleep(10)

    # now you can apply to db again to get a new df

希望答案对你有用。你知道吗

相关问题 更多 >