简体   繁体   English

在函数内在Pandas中追加数据框

[英]Append Dataframe in Pandas within a function

I'm using this function and APScheduler to add rows to a Dataframe everyhour. 我正在使用此功能和APScheduler每小时将行添加到Dataframe中。 The problem is every time it runs it overwrites the previous entry so its not really "appending" anything. 问题在于,每次运行它都会覆盖上一个条目,因此它并没有真正“追加”任何内容。

def SMSx(frame):
    SMS(frame)
    frame = frame.append(SMS.SMSdf)
    frame = frame[frame.a != "test"]
    frame = DataFrame(frame, columns=['Time', 'Hour', 'Date', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'Total', 'Bucket'])
    frame.to_excel('Sprint_Log.xlsx', 'Sheet 1', index=False)
    SMSx.frame = frame

If I use the exact same code (below) and run it manually it works just fine. 如果我使用完全相同的代码(如下)并手动运行它,则效果很好。 I'm not too sure what is going on here. 我不太确定这是怎么回事。 SMS.SMSdf is a data frame from the SMS function. SMS.SMSdf是来自SMS功能的数据帧。

SMS(frame)
frame = frame.append(SMS.SMSdf)
frame = frame[frame.a != "test"]
frame = DataFrame(frame, columns=['Time', 'Hour', 'Date', 'Day', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'Total', 'Bucket'])
frame.to_excel('Sprint_Log.xlsx', 'Sheet 1', index=False)
SMSx.frame = frame

Thank you for the help! 感谢您的帮助!

Code that worked: 起作用的代码:

def SMSx(frame_temp, frame_perm):
    SMS(frame_temp)
    try:
        frame_perm = DataFrame.from_csv('Sprint_Log.csv')
    except:
        pass
    frame_perm = frame_perm.append(SMS.SMSdf)
    frame_perm = frame_perm.drop_duplicates()
    frame_perm = frame_perm[frame_perm.Ready != "test"]
    frame_perm = DataFrame(frame_perm, columns=['Time', 'Hour', 'Date', 'Day', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'Total', 'Bucket'])
    frame_perm.to_csv('Sprint_Log.csv')
    SMSx.frame2 = frame_perm

The issue I suspect is that you do not return the updated frame variable. 我怀疑的问题是您没有return更新的frame变量。 While you assign to the SMSx variable in the function scope, as soon as the function exits that is lost. 在函数范围内分配SMSx变量时,函数退出后立即丢失。 I'm not sure how this is working however, since you do not first define the SMSx variable (it's the name of the current function, or is also a global variable?) 我不确定这是如何工作的,因为您没有先定义SMSx变量(它是当前函数的名称,还是全局变量?)

def SMSx(frame):
    SMS(frame)
    frame = frame.append(SMS.SMSdf)
    frame = frame[frame.a != "test"]
    frame = DataFrame(frame, columns=['Time', 'Hour', 'Date', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'Total', 'Bucket'])
    frame.to_excel('Sprint_Log.xlsx', 'Sheet 1', index=False)
    return frame


while True:
     frame = SMSx(frame)  # The returned frame will be used on the next iteration

Without seeing the rest of your code, it's pretty difficult to see what you're trying to do. 没有看到其余的代码,很难看到您要执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM