Appending rows to a Pandas DataFrame
Start your free 7-days trial now!
To append a row (a list or Series) to a Pandas DataFrame, use the DataFrame's append(~) method.
For performance, instead of appending rows one by one, opt to append rows at once.
Appending a single row
Consider the following DataFrame:
df
A B0 3 51 4 6
From a list
To use append(~), we first need to convert our row, which is initially represented as a list, to a Series:
Here, note the following:
the index of the Series
shas been set to the column labels ofdf(AandB) - otherwise, theappend(~)method won't vertically stack them.we set
ignore_index=Trueto ignore the index ofs- otherwise, we would have duplicate values in the new index0 1 0.a new DataFrame is returned, and the original
dfis kept is intact.
From a Series
Consider the same DataFrame:
df
A B0 3 51 4 6
Suppose we wanted to append the following Series to df:
Here, notice how the index of the Series has been set as the column labels - otherwise, the append(~) method won't vertically stack them.
Now, call append(~) like so:
A B0 3 51 4 62 10 11
The ignore_index=True is required because we did not assign a name to our Series s, and so Pandas does not know what row label to use when it is added to the DataFrame. Passing ignore_index tells Pandas to use the default integer index, which in this case is 2.
Appending multiple rows
Consider the same df as above:
df
A B0 3 51 4 6
From a nested list
To append multiple rows that are represented as a nested list:
Here, we are first creating an intermediate DataFrame out of my_list:
We then call append(~) to vertically stack the DataFrames. The ignore_index=True tells Pandas to use the default integer index in the resulting DataFrame - otherwise we would have gotten duplicate index [0,1,0,1].
From a list of Series
To append multiple rows represented as a list of Series:
Notice how, in this case, we do not need to create an intermediate DataFrame. This is because append(~) can handle a list of Series by default.