Append python dataframe not appending properly

I have the following code:

import pandas as pd
df2 = pd.DataFrame(dataset)

df = pd.read_excel (r'C:/adhoc/test.xlsx')

df.append(df2,ignore_index=True)

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(r'C:/adhoc/test.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

I am trying to take df2 (the current dataset) and append it into the already exiting data (df) and write that all back into the file. Essentially take the new data and append it to the bottom of the sheet. When I run this code all it does it add an extra index column beside the already exiting index column

Answer

The method “append” doesn’t change the dataframe, instead it returns another dataframe with the data of both dataframes. Therefore, you have to save the new dataframe in a variable. The code should resemble the following:

    df2 = df.append(df2, ignore_index=True)
    df2.to_excel('mi_file.xlsx', sheet_name = 'Sheet1')

Leave a Reply

Your email address will not be published. Required fields are marked *