Pandas DataFrame append() function With Examples

Pandas DataFrame append() function is used to merge rows from another DataFrame object. This function returns a new DataFrame object and doesn’t change the source objects. If there is a mismatch in the columns, the new columns are added in the result DataFrame.

1. Pandas DataFrame append() Parameters

The append() function syntax is:

  • other: The DataFrame, Series or Dict-like object whose rows will be added to the caller DataFrame.
  • ignore_index: if True, the indexes from the source DataFrame objects are ignored.
  • verify_integrity: if True, raise ValueError on creating index with duplicates.
  • sort: sort columns if the source DataFrame columns are not aligned. This functionality is deprecated. So we have to pass sort=True to sort and silence the warning message. If sort=False is passed, the columns are not sorted and warning is ignored.

Let’s look into some examples of the DataFrame append() function.

2. Appending Two DataFrames

Output:

3. Appending and Ignoring DataFrame Indexes

If you look at the previous example, the output contains duplicate indexes. We can pass ignore_index=True to ignore the source indexes and assign new index to the output DataFrame.

Output:

4. Raise ValueError for duplicate indexes

We can pass verify_integrity=True to raise ValueError if there are duplicate indexes in the two DataFrame objects.

Output:

Let’s look at another example where we don’t have duplicate indexes.

Output:

5. Appending DataFrame objects with Non-Matching Columns

Output:

We are explicitly passing sort=False to avoid sorting of columns and ignore FutureWarning. If you don’t pass this parameter, the output will contain the following warning message.

Let’s see what happens when we pass sort=True.

Output:

Notice that the columns are sorted in the result DataFrame object. Note that this feature is deprecated and will be removed from future releases.

Let’s look at another example where we have non-matching columns with int values.

Output:

Notice that the ID values are changed to floating-point numbers to allow NaN value.

6. References

By admin

Leave a Reply

%d bloggers like this: