如何在Python中将本地数据框附加到全局数据框?

时间:2017-03-05 22:59:40

标签: python

我试图从定义函数的每次调用创建一个表,并将表附加在一起。但是当我第一次调用函数并使用输出填充表corr_tb时它可以工作。但是当我再次调用该函数并期望将新输出附加到corr_tb时。什么都没发生。表corr_tb不会更改。那是因为全局变量还是局部变量?

corr_tb = pd.DataFrame()

def corr_tbl(df, key, var, with_var):
    #calculate correlation by key
    output = pd.DataFrame(df.groupby(key)[[var, with_var]].corr().ix[1::2,var]).reset_index()[key+[var]]

    global corr_tb 
    if corr_tb.empty:
        corr_tb = output
    else:
        corr_tb.append(output)
        #print(output.head()) #result could be print but cannot be appended

#call function
corr_tbl(final, ['key1','key2'], 'var1','Sales')
corr_tbl(final, ['key1','key2'], 'var2','Sales')

1 个答案:

答案 0 :(得分:0)

pandas.DataFrame.append方法不修改原始对象但返回新对象,您可以将新对象重新分配回corr_tb

def corr_tbl(...)
    # did some calculation here
    if ...:
        # 
    else:
        corr_tb = corr_tb.append(df)        # <<<<<< try modifying this line