有没有一种方法可以从类内部的方法操作全局数据框?

时间:2020-09-16 22:31:28

标签: python dataframe tkinter

我正在制作一个tkinter应用程序,其中在调用函数Add_Task_Timing()时,它将在类Task的方法内创建一个临时数据帧。以下是代码的格式:

# Makes a global dataframe
Task_Dataframe = pd.DataFrame()
Task_Dataframe.loc[0, 'Task_Name'] = [None]
Task_Dataframe.loc[0, 'Start_Time'] = [None]
Task_Dataframe.loc[0, 'End_Time'] = [None]
Task_Dataframe.loc[0, 'Duration'] = [None]
Task_Dataframe.loc[0, 'Team_Member'] = [None]


class Task():

    def __init__(self,task_name, start_time, end_time):
        # THIS METHOD CREATES ATTRIBUTES OF THE TASK
        self.task_name = task_name
        self.start_time = start_time
        self.end_time = end_time
        

    def Add_Task_Timing (self):  
        # THIS METHOD ADDS THE TASK TO THE DATAFRAME

        
        # column_names = ["Task_Name", "Start_Time","End_Time","Duration", "Team_Member"]

        temporary_df = pd.DataFrame()
        temporary_df.loc[0, 'Task_Name'] = [task_name]
        temporary_df.loc[0, 'Start_Time'] = [start_time]
        temporary_df.loc[0, 'End_Time'] = [end_time]
        temporary_df.loc[0, 'Duration'] = [end_time - start_time]
        temporary_df.loc[0, 'Team_Member'] = [None]
        print(temporary_df)
        
        Task_Dataframe.join(temporary_df, lsuffix='_MAIN', rsuffix='_TEMP')
        
        return Task_Dataframe

我唯一的问题是方法Add_Task_Timing()内部的操作不会发生在全局数据帧Task_Dataframe上。由于某种原因,返回方法Add_Task_Timing()的输出显示:

  Task_Name Start_Time End_Time Duration Team_Member
0    NaN       NaN         NaN      NaN       NaN

我了解由于某种原因,该方法未更新为全局数据帧定义的值。我已经尝试过concat()join()append()。似乎没有办法解决问题。

1 个答案:

答案 0 :(得分:0)

我添加了以下几行:

global Task_Dataframe
Task_Dataframe = Task_Dataframe.join(temporary_df, lsuffix='_M', rsuffix='_T')

temporary_df为:

  Task_Name  Start_Time  End_Time  Duration  Team_Member
0   tasking        23.0      43.0      20.0          NaN

temporary_df的结果是:

 Task_Name_Main  Start_Time_Main  End_Time_Main  Duration_Main  ...  Start_Time_Temp End_Time_Temp  Duration_Temp  Team_Member_Temp
0          NaN           NaN         NaN         NaN  ...                   43.0         23.0            20.0       NaN

我仍在设法弄清为什么它不更新全局数据帧Task_Dataframe中的值。