首页 > 解决方案 > 如何将函数的输出存储到单独的数据帧中?

问题描述

我正在尝试使用一个函数处理多个数据帧,并将结果存储在单独的相应数据帧中。但是,该函数似乎没有正确存储变量。

这是功能:

def customize_df(in_df,out_df,old_col_val,new_col_val,vol):
    out_df = in_df.copy()
    # Adjust hemisphere contigent values
    if 'lh' in out_df:
        out_df.columns = out_df.columns.str.replace('lh_', 'L_')
    if 'rh' in out_df:
        out_df.columns = out_df.columns.str.replace('rh_', 'R_')
    # Adjust column names.
    out_df.columns = out_df.columns.str.replace(old_col_val, new_col_val)
    # Change the name of the first column to ID.
    out_df.columns = out_df.columns.str.replace(out_df.columns[0], "ID")
    # Make Volumetric eTIV adjustments
    if vol==True:
        df_raw = out_df.copy()
        df_raw.columns = df_raw.columns.str.replace('_Vol', '_Vol_Raw')
        df_raw.columns = df_raw.columns.str.replace('_volume', '_Vol_Raw')
        df_raw = pd.DataFrame(data = df_raw, columns= df_raw.columns)
        df2 = out_df.copy()
        df2.columns = df2.columns.str.replace('_volume', '_Vol_Adj')
        df2 = pd.DataFrame(data = df2, columns= df2.columns)
        cols = out_df.columns[out_df.columns.str.contains('_Adj')].tolist()
        for col in cols:
            df2[col] = df2[col].div(df2['eTIV'], axis=0)
        df_combined= df_raw.join(df2, rsuffix='_DROP')
        cols = df_combined.columns[df_combined.columns.str.contains('_DROP')].tolist()
        for col in cols:
            df_combined = df_combined.drop([col], axis=1)
        out_df = df_combined.copy()
        return out_df
    elif vol==False:
        return out_df

它按预期工作,但是,当我使用多个顺序输入运行 then 函数时,结果似乎没有按预期存储到“out_df”中。

以下是命令:

customize_df(lh_exvivo_Area,'lh_ExV_Area','_exvivo_area','_ExV_Area',vol=True)

customize_df(Sub_GM_Vol,'Sub_GM_Vol','','_Sub_GM_Vol',vol=True)

customize_df(Sub_WM_Vol,'Sub_WM_Vol','','_Sub_WM_Vol',vol=True)

当我通过输入所需输出数据框的名称对其进行测试时,没有结果。

lh_ExV_Area.head()

NameError: name 'lh_ExV_Area' is not defined

标签: pythonpython-3.xpandasdataframe

解决方案


推荐阅读