Python Forum
append dataframes in loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/Forum-Python-Coding)
+--- Forum: Data Science (https://python-forum.io/Forum-Data-Science)
+--- Thread: append dataframes in loop (/Thread-append-dataframes-in-loop)



append dataframes in loop - ghena - Feb-17-2020

Hi,
I have a code with two dataframes types which are collected by simulation. I want to append these dataframes and store them into separated csv. When I print the dataframes within the loop, it was fine, but when I print the aggregated dataframe outside the loop, it is empty.

df1 = pd.DataFrame()
df2 = pd.DataFrame()
for i in range(n):
    df_temp1 = get_df1(i)
    df1.append(df_temp1, ignore_index=True)

    df_temp2 = get_df2(i)
    df2.append(df_temp2,ignote_index=True)

df1.to_csv('f1.csv')
df2.to_csv('f2.csv')
Any hint?

Thanks


RE: append dataframes in loop - jefsummers - Feb-17-2020

df1.append returns a new object So, change lines 5-8 to
    df1 = df1.append(df_temp1, ignore_index = True)
    df_temp2 = get_df2(i)
    df2 = df2.append(df_temp2,ignore_index=True)
and it will work fine.