如何在不将数据框分配给变量的情况下(在心理学中)从函数内部全局访问数据框?
How to make a dataframe globally accessible from within a function without assigning it to a variable (in psychopy)?
我有一个函数可以执行多个命令并在最后创建一个数据框:
def Pos_Presentation():
df = pd.DataFrame(columns=['ID', 'Date', 'Time', 'Session','Condition','Stimulus','Response_Type','Reaction_Time'])
return df
我想要在函数外部创建和访问数据框 (df)。但是当我尝试时:
Pos_Presentation()
df
我得到一个错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-00cf07b74dcd> in <module>
----> 1 df
NameError: name 'df' is not defined
我试过了:
def Pos_Presentation():
global df
df = pd.DataFrame(columns=['ID', 'Date', 'Time', 'Session','Condition','Stimulus','Response_Type','Reaction_Time'])
return df
Pos_Presentation()
df
在 Jupyter_Notebook 中,这有效。但是在我需要 运行 的 Psychopy 中,它给了我一个错误:
NameError: name 'df' is not defined
我无法将此函数分配给变量(例如,var = Pos_Presentation()),因为除了生成数据帧之外,它还做了很多其他事情。
我想你只需要将 PosPresentation() 的输出分配给 df,就像这样:
def Pos_Presentation():
global df
df = pd.DataFrame(columns=['ID', 'Date', 'Time', 'Session','Condition','Stimulus','Response_Type','Reaction_Time'])
return df
df = Pos_Presentation()
此外,我认为您的函数定义中不需要 "global df",如果您给它们不同的名称(例如,调用函数 "df" 但函数 "Pos_df" 之外的那个。
我有一个函数可以执行多个命令并在最后创建一个数据框:
def Pos_Presentation():
df = pd.DataFrame(columns=['ID', 'Date', 'Time', 'Session','Condition','Stimulus','Response_Type','Reaction_Time'])
return df
我想要在函数外部创建和访问数据框 (df)。但是当我尝试时:
Pos_Presentation()
df
我得到一个错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-00cf07b74dcd> in <module>
----> 1 df
NameError: name 'df' is not defined
我试过了:
def Pos_Presentation():
global df
df = pd.DataFrame(columns=['ID', 'Date', 'Time', 'Session','Condition','Stimulus','Response_Type','Reaction_Time'])
return df
Pos_Presentation()
df
在 Jupyter_Notebook 中,这有效。但是在我需要 运行 的 Psychopy 中,它给了我一个错误:
NameError: name 'df' is not defined
我无法将此函数分配给变量(例如,var = Pos_Presentation()),因为除了生成数据帧之外,它还做了很多其他事情。
我想你只需要将 PosPresentation() 的输出分配给 df,就像这样:
def Pos_Presentation():
global df
df = pd.DataFrame(columns=['ID', 'Date', 'Time', 'Session','Condition','Stimulus','Response_Type','Reaction_Time'])
return df
df = Pos_Presentation()
此外,我认为您的函数定义中不需要 "global df",如果您给它们不同的名称(例如,调用函数 "df" 但函数 "Pos_df" 之外的那个。