Adding a row to a pandas database

154 views Asked by At

I'm trying to add a row to an empty data frame but I'm having issues with adding it with the following code. If anybody could suggest a fix I'd appreciate it.

Code:

df = pd.DataFrame(columns=['Year','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
new_row = {'Year':2020,'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}
df.append(new_row,ignore_index=True)
print(df)

Result:

Empty DataFrame
Columns: [Year, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
Index: []
1

There are 1 answers

0
mozway On BEST ANSWER

The append method does not work in place but returns a new DataFrame, you need to save the output:

df = df.append(new_row, ignore_index=True)

NB. keep in mind that append is slow. It is fine to use once, but if you need to repeatedly append new rows better construct a list an call once the DataFrame constructor.