Search

pandas provides various facilities for easily combining together Series,
DataFrame, and Panel objects with various kinds of set logic for the indexes
and relational algebra functionality in the case of join / merge-type
operations.

The concat() function (in the main pandas namespace) does all of
the heavy lifting of performing concatenation operations along an axis while
performing optional set logic (union or intersection) of the indexes (if any) on
the other axes. Note that I say “if any” because there is only a single possible
axis of concatenation for Series.

Before diving into all of the details of concat and what it can do, here is
a simple example:

Like its sibling function on ndarrays, numpy.concatenate, pandas.concat
takes a list or dict of homogeneously-typed objects and concatenates them with
some configurable handling of “what to do with the other axes”:

objs : a sequence or mapping of Series, DataFrame, or Panel objects. If a
dict is passed, the sorted keys will be used as the keys argument, unless
it is passed, in which case the values will be selected (see below). Any None
objects will be dropped silently unless they are all None in which case a
ValueError will be raised.

axis : {0, 1, …}, default 0. The axis to concatenate along.

join : {‘inner’, ‘outer’}, default ‘outer’. How to handle indexes on
other axis(es). Outer for union and inner for intersection.

ignore_index : boolean, default False. If True, do not use the index
values on the concatenation axis. The resulting axis will be labeled 0, …,
n - 1. This is useful if you are concatenating objects where the
concatenation axis does not have meaningful indexing information. Note
the index values on the other axes are still respected in the join.

join_axes : list of Index objects. Specific indexes to use for the other
n - 1 axes instead of performing inner/outer set logic.

Without a little bit of context many of these arguments don’t make much sense.
Let’s revisit the above example. Suppose we wanted to associate specific keys
with each of the pieces of the chopped up DataFrame. We can do this using the
keys argument:

In [6]: result=pd.concat(frames,keys=['x','y','z'])

As you can see (if you’ve read the rest of the documentation), the resulting
object’s index has a hierarchical index. This
means that we can now select out each chunk by key:

It’s not a stretch to see how this can be very useful. More detail on this
functionality below.

Note

It is worth noting that concat() (and therefore
append()) makes a full copy of the data, and that constantly
reusing this function can create a significant performance hit. If you need
to use the operation over several datasets, use a list comprehension.

The default behavior with join='outer' is to sort the other axis
(columns in this case). In a future version of pandas, the default will
be to not sort. We specified sort=False to opt in to the new
behavior now.

Here is the same thing with join='inner':

In [10]: result=pd.concat([df1,df4],axis=1,join='inner')

Lastly, suppose we just wanted to reuse the exact index from the original
DataFrame:

Since we’re concatenating a Series to a DataFrame, we could have
achieved the same result with DataFrame.assign(). To concatenate an
arbitrary number of pandas objects (DataFrame or Series), use
concat.

A fairly common use of the keys argument is to override the column names
when creating a new DataFrame based on existing Series.
Notice how the default behaviour consists on letting the resulting DataFrame
inherit the parent Series’ name, when these existed.

You should use ignore_index with this method to instruct DataFrame to
discard its index. If you wish to preserve the index, you should construct an
appropriately-indexed DataFrame and append or concatenate those objects.

pandas has full-featured, high performance in-memory join operations
idiomatically very similar to relational databases like SQL. These methods
perform significantly better (in some cases well over an order of magnitude
better) than other open source implementations (like base::merge.data.frame
in R). The reason for this is careful algorithmic design and the internal layout
of the data in DataFrame.

on: Column or index level names to join on. Must be found in both the left
and right DataFrame objects. If not passed and left_index and
right_index are False, the intersection of the columns in the
DataFrames will be inferred to be the join keys.

left_on: Columns or index levels from the left DataFrame to use as
keys. Can either be column names, index level names, or arrays with length
equal to the length of the DataFrame.

right_on: Columns or index levels from the right DataFrame to use as
keys. Can either be column names, index level names, or arrays with length
equal to the length of the DataFrame.

left_index: If True, use the index (row labels) from the left
DataFrame as its join key(s). In the case of a DataFrame with a MultiIndex
(hierarchical), the number of levels must match the number of join keys
from the right DataFrame.

right_index: Same usage as left_index for the right DataFrame

how: One of 'left', 'right', 'outer', 'inner'. Defaults
to inner. See below for more detailed description of each method.

sort: Sort the result DataFrame by the join keys in lexicographical
order. Defaults to True, setting to False will improve performance
substantially in many cases.

suffixes: A tuple of string suffixes to apply to overlapping
columns. Defaults to ('_x','_y').

copy: Always copy data (default True) from the passed DataFrame
objects, even when reindexing is not necessary. Cannot be avoided in many
cases but may improve performance / memory usage. The cases where copying
can be avoided are somewhat pathological but this option is provided
nonetheless.

indicator: Add a column to the output DataFrame called _merge
with information on the source of each row. _merge is Categorical-type
and takes on a value of left_only for observations whose merge key
only appears in 'left' DataFrame, right_only for observations whose
merge key only appears in 'right' DataFrame, and both if the
observation’s merge key is found in both.

“one_to_one” or “1:1”: checks if merge keys are unique in both
left and right datasets.

“one_to_many” or “1:m”: checks if merge keys are unique in left
dataset.

“many_to_one” or “m:1”: checks if merge keys are unique in right
dataset.

“many_to_many” or “m:m”: allowed, but does not result in checks.

New in version 0.21.0.

Note

Support for specifying index levels as the on, left_on, and
right_on parameters was added in version 0.23.0.

The return type will be the same as left. If left is a DataFrame
and right is a subclass of DataFrame, the return type will still be
DataFrame.

merge is a function in the pandas namespace, and it is also available as a
DataFrame instance method merge(), with the calling
DataFrame being implicitly considered the left object in the join.

The related join() method, uses merge internally for the
index-on-index (by default) and column(s)-on-index join. If you are joining on
index only, you may wish to use DataFrame.join to save yourself some typing.

Experienced users of relational databases like SQL will be familiar with the
terminology used to describe join operations between two SQL-table like
structures (DataFrame objects). There are several cases to consider which
are very important to understand:

one-to-one joins: for example when joining two DataFrame objects on
their indexes (which must contain unique values).

many-to-one joins: for example when joining an index (unique) to one or
more columns in a different DataFrame.

many-to-many joins: joining columns on columns.

Note

When joining columns on columns (potentially a many-to-many join), any
indexes on the passed DataFrame objects will be discarded.

It is worth spending some time understanding the result of the many-to-many
join case. In SQL / standard relational algebra, if a key combination appears
more than once in both tables, the resulting table will have the Cartesian
product of the associated data. Here is a very basic example with one unique
key combination:

The how argument to merge specifies how to determine which keys are to
be included in the resulting table. If a key combination does not appear in
either the left or right tables, the values in the joined table will be
NA. Here is a summary of the how options and their SQL equivalent names:

Joining / merging on duplicate keys can cause a returned frame that is the multiplication of the row dimensions, which may result in memory overflow. It is the user’ s responsibility to manage duplicate values in keys before joining large DataFrames.

Users can use the validate argument to automatically check whether there
are unexpected duplicates in their merge keys. Key uniqueness is checked before
merge operations and so should protect against memory overflows. Checking key
uniqueness is also a good way to ensure user data structures are as expected.

In the following example, there are duplicate values of B in the right
DataFrame. As this is not a one-to-one merge – as specified in the
validate argument – an exception will be raised.

In [53]: result=pd.merge(left,right,on='B',how='outer',validate="one_to_one")...MergeError: Merge keys are not unique in right dataset; not a one-to-one merge

If the user is aware of the duplicates in the right DataFrame but wants to
ensure there are no duplicates in the left DataFrame, one can use the
validate='one_to_many' argument instead, which will not raise an exception.