Appending rows to a Pandas DataFrame
Start your free 7-days trial now!
To append a row (a
Series) to a Pandas DataFrame, use the DataFrame's
For performance, instead of appending rows one by one, opt to append rows at once.
Appending a single row
Consider the following DataFrame:
From a list
append(~), we first need to convert our row, which is initially represented as a
list, to a
Here, note the following:
the index of the Series
shas been set to the column labels of
B) - otherwise, the
append(~)method won't vertically stack them.
ignore_index=Trueto ignore the index of
s- otherwise, we would have duplicate values in the new index
0 1 0.
a new DataFrame is returned, and the original
dfis kept is intact.
From a Series
Consider the same DataFrame:
Suppose we wanted to append the following Series to
Here, notice how the index of the Series has been set as the column labels - otherwise, the
append(~) method won't vertically stack them.
append(~) like so:
A B0 3 51 4 62 10 11
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
Appending multiple rows
Consider the same
df as above:
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
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
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.