Merge, join, and concatenate

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.

Concatenating objects

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:

In [1]: df1 = DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
   ...:                  'B': ['B0', 'B1', 'B2', 'B3'],
   ...:                  'C': ['C0', 'C1', 'C2', 'C3'],
   ...:                  'D': ['D0', 'D1', 'D2', 'D3']},
   ...:                 index=[0, 1, 2, 3])
   ...: 

In [2]: df2 = DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
   ...:                  'B': ['B4', 'B5', 'B6', 'B7'],
   ...:                  'C': ['C4', 'C5', 'C6', 'C7'],
   ...:                  'D': ['D4', 'D5', 'D6', 'D7']},
   ...:                 index=[4, 5, 6, 7])
   ...: 

In [3]: df3 = DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],
   ...:                  'B': ['B8', 'B9', 'B10', 'B11'],
   ...:                  'C': ['C8', 'C9', 'C10', 'C11'],
   ...:                  'D': ['D8', 'D9', 'D10', 'D11']},
   ...:                 index=[8, 9, 10, 11])
   ...: 

In [4]: frames = [df1, df2, df3]

In [5]: result = concat(frames)
_images/merging_concat_basic.png

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”:

concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
       keys=None, levels=None, names=None, verify_integrity=False)
  • objs: list or dict 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)
  • 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
  • join_axes: list of Index objects. Specific indexes to use for the other n - 1 axes instead of performing inner/outer set logic
  • keys: sequence, default None. Construct hierarchical index using the passed keys as the outermost level If multiple levels passed, should contain tuples.
  • levels : list of sequences, default None. If keys passed, specific levels to use for the resulting MultiIndex. Otherwise they will be inferred from the keys
  • names: list, default None. Names for the levels in the resulting hierarchical index
  • verify_integrity: boolean, default False. Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation
  • 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.

Without a little bit of context and example many of these arguments don’t make much sense. Let’s take 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 = concat(frames, keys=['x', 'y', 'z'])
_images/merging_concat_keys.png

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 do stuff like select out each chunk by key:

In [7]: result.ix['y']
Out[7]: 
    A   B   C   D
4  A4  B4  C4  D4
5  A5  B5  C5  D5
6  A6  B6  C6  D6
7  A7  B7  C7  D7

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

Note

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

frames = [ process_your_file(f) for f in files ]
result = pd.concat(frames)

Set logic on the other axes

When gluing together multiple DataFrames (or Panels or...), for example, you have a choice of how to handle the other axes (other than the one being concatenated). This can be done in three ways:

  • Take the (sorted) union of them all, join='outer'. This is the default option as it results in zero information loss.
  • Take the intersection, join='inner'.
  • Use a specific index (in the case of DataFrame) or indexes (in the case of Panel or future higher dimensional objects), i.e. the join_axes argument

Here is a example of each of these methods. First, the default join='outer' behavior:

In [8]: df4 = DataFrame({'B': ['B2', 'B3', 'B6', 'B7'],
   ...:                  'D': ['D2', 'D3', 'D6', 'D7'],
   ...:                  'F': ['F2', 'F3', 'F6', 'F7']},
   ...:                 index=[2, 3, 6, 7])
   ...: 

In [9]: result = concat([df1, df4], axis=1)
_images/merging_concat_axis1.png

Note that the row indexes have been unioned and sorted. Here is the same thing with join='inner':

In [10]: result = concat([df1, df4], axis=1, join='inner')
_images/merging_concat_axis1_inner.png

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

In [11]: result = concat([df1, df4], axis=1, join_axes=[df1.index])
_images/merging_concat_axis1_join_axes.png

Concatenating using append

A useful shortcut to concat are the append instance methods on Series and DataFrame. These methods actually predated concat. They concatenate along axis=0, namely the index:

In [12]: result = df1.append(df2)
_images/merging_append1.png

In the case of DataFrame, the indexes must be disjoint but the columns do not need to be:

In [13]: result = df1.append(df4)
_images/merging_append2.png

append may take multiple objects to concatenate:

In [14]: result = df1.append([df2, df3])
_images/merging_append3.png

Note

Unlike list.append method, which appends to the original list and returns nothing, append here does not modify df1 and returns its copy with df2 appended.

Ignoring indexes on the concatenation axis

For DataFrames which don’t have a meaningful index, you may wish to append them and ignore the fact that they may have overlapping indexes:

To do this, use the ignore_index argument:

In [15]: result = concat([df1, df4], ignore_index=True)
_images/merging_concat_ignore_index.png

This is also a valid argument to DataFrame.append:

In [16]: result = df1.append(df4, ignore_index=True)
_images/merging_append_ignore_index.png

Concatenating with mixed ndims

You can concatenate a mix of Series and DataFrames. The Series will be transformed to DataFrames with the column name as the name of the Series.

In [17]: s1 = Series(['X0', 'X1', 'X2', 'X3'], name='X')

In [18]: result = concat([df1, s1], axis=1)
_images/merging_concat_mixed_ndim.png

If unnamed Series are passed they will be numbered consecutively.

In [19]: s2 = Series(['_0', '_1', '_2', '_3'])

In [20]: result = concat([df1, s2, s2, s2], axis=1)
_images/merging_concat_unnamed_series.png

Passing ignore_index=True will drop all name references.

In [21]: result = concat([df1, s1], axis=1, ignore_index=True)
_images/merging_concat_series_ignore_index.png

More concatenating with group keys

Let’s consider a variation on the first example presented:

In [22]: result = concat(frames, keys=['x', 'y', 'z'])
_images/merging_concat_group_keys2.png

You can also pass a dict to concat in which case the dict keys will be used for the keys argument (unless other keys are specified):

In [23]: pieces = {'x': df1, 'y': df2, 'z': df3}

In [24]: result = concat(pieces)
_images/merging_concat_dict.png
In [25]: result = concat(pieces, keys=['z', 'y'])
_images/merging_concat_dict_keys.png

The MultiIndex created has levels that are constructed from the passed keys and the index of the DataFrame pieces:

In [26]: result.index.levels
Out[26]: FrozenList([[u'z', u'y'], [4, 5, 6, 7, 8, 9, 10, 11]])

If you wish to specify other levels (as will occasionally be the case), you can do so using the levels argument:

In [27]: result = concat(pieces, keys=['x', 'y', 'z'],
   ....:                 levels=[['z', 'y', 'x', 'w']],
   ....:                 names=['group_key'])
   ....: 
_images/merging_concat_dict_keys_names.png
In [28]: result.index.levels
Out[28]: FrozenList([[u'z', u'y', u'x', u'w'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

Yes, this is fairly esoteric, but is actually necessary for implementing things like GroupBy where the order of a categorical variable is meaningful.

Appending rows to a DataFrame

While not especially efficient (since a new object must be created), you can append a single row to a DataFrame by passing a Series or dict to append, which returns a new DataFrame as above.

In [29]: s2 = Series(['X0', 'X1', 'X2', 'X3'], index=['A', 'B', 'C', 'D'])

In [30]: result = df1.append(s2, ignore_index=True)
_images/merging_append_series_as_row.png

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.

You can also pass a list of dicts or Series:

In [31]: dicts = [{'A': 1, 'B': 2, 'C': 3, 'X': 4},
   ....:          {'A': 5, 'B': 6, 'C': 7, 'Y': 8}]
   ....: 

In [32]: result = df1.append(dicts, ignore_index=True)
_images/merging_append_dits.png

Database-style DataFrame joining/merging

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 internal layout of the data in DataFrame.

See the cookbook for some advanced strategies.

Users who are familiar with SQL but new to pandas might be interested in a comparison with SQL.

pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects:

merge(left, right, how='inner', on=None, left_on=None, right_on=None,
      left_index=False, right_index=False, sort=True,
      suffixes=('_x', '_y'), copy=True)

Here’s a description of what each argument is for:

  • left: A DataFrame object
  • right: Another DataFrame object
  • on: Columns (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 from the left DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame
  • right_on: Columns from the right DataFrame to use as keys. Can either be column 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.

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, with the calling DataFrame being implicitly considered the left object in the join.

The related DataFrame.join method, uses merge internally for the index-on-index and index-on-column(s) joins, but joins on indexes by default rather than trying to join on common columns (the default behavior for merge). If you are joining on index, you may wish to use DataFrame.join to save yourself some typing.

Brief primer on merge methods (relational algebra)

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 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:

In [33]: left = DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
   ....:                   'A': ['A0', 'A1', 'A2', 'A3'],
   ....:                   'B': ['B0', 'B1', 'B2', 'B3']})
   ....: 

In [34]: right = DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
   ....:                    'C': ['C0', 'C1', 'C2', 'C3'],
   ....:                    'D': ['D0', 'D1', 'D2', 'D3']})
   ....: 

In [35]: result = merge(left, right, on='key')
_images/merging_merge_on_key.png

Here is a more complicated example with multiple join keys:

In [36]: left = DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
   ....:                   'key2': ['K0', 'K1', 'K0', 'K1'],
   ....:                   'A': ['A0', 'A1', 'A2', 'A3'],
   ....:                   'B': ['B0', 'B1', 'B2', 'B3']})
   ....: 

In [37]: right = DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
   ....:                    'key2': ['K0', 'K0', 'K0', 'K0'],
   ....:                    'C': ['C0', 'C1', 'C2', 'C3'],
   ....:                    'D': ['D0', 'D1', 'D2', 'D3']})
   ....: 

In [38]: result = merge(left, right, on=['key1', 'key2'])
_images/merging_merge_on_key_multiple.png

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:

Merge method SQL Join Name Description
left LEFT OUTER JOIN Use keys from left frame only
right RIGHT OUTER JOIN Use keys from right frame only
outer FULL OUTER JOIN Use union of keys from both frames
inner INNER JOIN Use intersection of keys from both frames
In [39]: result = merge(left, right, how='left', on=['key1', 'key2'])
_images/merging_merge_on_key_left.png
In [40]: result = merge(left, right, how='right', on=['key1', 'key2'])
_images/merging_merge_on_key_right.png
In [41]: result = merge(left, right, how='outer', on=['key1', 'key2'])
_images/merging_merge_on_key_outer.png
In [42]: result = merge(left, right, how='inner', on=['key1', 'key2'])
_images/merging_merge_on_key_inner.png

Joining on index

DataFrame.join is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. Here is a very basic example:

In [43]: left = DataFrame({'A': ['A0', 'A1', 'A2'],
   ....:                   'B': ['B0', 'B1', 'B2']},
   ....:                  index=['K0', 'K1', 'K2'])
   ....: 

In [44]: right = DataFrame({'C': ['C0', 'C2', 'C3'],
   ....:                    'D': ['D0', 'D2', 'D3']},
   ....:                   index=['K0', 'K2', 'K3'])
   ....: 

In [45]: result = left.join(right)
_images/merging_join.png
In [46]: result = left.join(right, how='outer')
_images/merging_join_outer.png
In [47]: result = left.join(right, how='inner')
_images/merging_join_inner.png

The data alignment here is on the indexes (row labels). This same behavior can be achieved using merge plus additional arguments instructing it to use the indexes:

In [48]: result = merge(left, right, left_index=True, right_index=True, how='outer')
_images/merging_merge_index_outer.png
In [49]: result = merge(left, right, left_index=True, right_index=True, how='inner');
_images/merging_merge_index_inner.png

Joining key columns on an index

join takes an optional on argument which may be a column or multiple column names, which specifies that the passed DataFrame is to be aligned on that column in the DataFrame. These two function calls are completely equivalent:

left.join(right, on=key_or_keys)
merge(left, right, left_on=key_or_keys, right_index=True,
      how='left', sort=False)

Obviously you can choose whichever form you find more convenient. For many-to-one joins (where one of the DataFrame’s is already indexed by the join key), using join may be more convenient. Here is a simple example:

In [50]: left = DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
   ....:                   'B': ['B0', 'B1', 'B2', 'B3'],
   ....:                   'key': ['K0', 'K1', 'K0', 'K1']})
   ....: 

In [51]: right = DataFrame({'C': ['C0', 'C1'],
   ....:                    'D': ['D0', 'D1']},
   ....:                   index=['K0', 'K1'])
   ....: 

In [52]: result = left.join(right, on='key')
_images/merging_join_key_columns.png
In [53]: result = merge(left, right, left_on='key', right_index=True,
   ....:                how='left', sort=False);
   ....: 
_images/merging_merge_key_columns.png

To join on multiple keys, the passed DataFrame must have a MultiIndex:

In [54]: left = DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
   ....:                   'B': ['B0', 'B1', 'B2', 'B3'],
   ....:                   'key1': ['K0', 'K0', 'K1', 'K2'],
   ....:                   'key2': ['K0', 'K1', 'K0', 'K1']})
   ....: 

In [55]: index = MultiIndex.from_tuples([('K0', 'K0'), ('K1', 'K0'),
   ....:                                 ('K2', 'K0'), ('K2', 'K1')])
   ....: 

In [56]: right = DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
   ....:                    'D': ['D0', 'D1', 'D2', 'D3']},
   ....:                   index=index)
   ....: 

Now this can be joined by passing the two key column names:

In [57]: result = left.join(right, on=['key1', 'key2'])
_images/merging_join_multikeys.png

The default for DataFrame.join is to perform a left join (essentially a “VLOOKUP” operation, for Excel users), which uses only the keys found in the calling DataFrame. Other join types, for example inner join, can be just as easily performed:

In [58]: result = left.join(right, on=['key1', 'key2'], how='inner')
_images/merging_join_multikeys_inner.png

As you can see, this drops any rows where there was no match.

Joining a single Index to a Multi-index

New in version 0.14.0.

You can join a singly-indexed DataFrame with a level of a multi-indexed DataFrame. The level will match on the name of the index of the singly-indexed frame against a level name of the multi-indexed frame.

In [59]: left = DataFrame({'A': ['A0', 'A1', 'A2'],
   ....:                   'B': ['B0', 'B1', 'B2']},
   ....:                  index=Index(['K0', 'K1', 'K2'], name='key'))
   ....: 

In [60]: index = MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
   ....:                                 ('K2', 'Y2'), ('K2', 'Y3')],
   ....:                                names=['key', 'Y'])
   ....: 

In [61]: right = DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
   ....:                    'D': ['D0', 'D1', 'D2', 'D3']},
   ....:                   index=index)
   ....: 

In [62]: result = left.join(right, how='inner')
_images/merging_join_multiindex_inner.png

This is equivalent but less verbose and more memory efficient / faster than this.

In [63]: result = merge(left.reset_index(), right.reset_index(),
   ....:       on=['key'], how='inner').set_index(['key','Y'])
   ....: 
_images/merging_merge_multiindex_alternative.png

Joining with two multi-indexes

This is not Implemented via join at-the-moment, however it can be done using the following.

In [64]: index = MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'),
   ....:                                 ('K1', 'X2')],
   ....:                                names=['key', 'X'])
   ....: 

In [65]: left = DataFrame({'A': ['A0', 'A1', 'A2'],
   ....:                   'B': ['B0', 'B1', 'B2']},
   ....:                  index=index)
   ....: 

In [66]: result = merge(left.reset_index(), right.reset_index(),
   ....:                on=['key'], how='inner').set_index(['key','X','Y'])
   ....: 
_images/merging_merge_two_multiindex.png

Overlapping value columns

The merge suffixes argument takes a tuple of list of strings to append to overlapping column names in the input DataFrames to disambiguate the result columns:

In [67]: left = DataFrame({'k': ['K0', 'K1', 'K2'], 'v': [1, 2, 3]})

In [68]: right = DataFrame({'k': ['K0', 'K0', 'K3'], 'v': [4, 5, 6]})

In [69]: result = merge(left, right, on='k')
_images/merging_merge_overlapped.png
In [70]: result = merge(left, right, on='k', suffixes=['_l', '_r'])
_images/merging_merge_overlapped_suffix.png

DataFrame.join has lsuffix and rsuffix arguments which behave similarly.

In [71]: left = left.set_index('k')

In [72]: right = right.set_index('k')

In [73]: result = left.join(right, lsuffix='_l', rsuffix='_r')
_images/merging_merge_overlapped_multi_suffix.png

Joining multiple DataFrame or Panel objects

A list or tuple of DataFrames can also be passed to DataFrame.join to join them together on their indexes. The same is true for Panel.join.

In [74]: right2 = DataFrame({'v': [7, 8, 9]}, index=['K1', 'K1', 'K2'])

In [75]: result = left.join([right, right2])
_images/merging_join_multi_df.png

Merging Ordered Data

New in v0.8.0 is the ordered_merge function for combining time series and other ordered data. In particular it has an optional fill_method keyword to fill/interpolate missing data:

In [76]: left = DataFrame({'k': ['K0', 'K1', 'K1', 'K2'],
   ....:                   'lv': [1, 2, 3, 4],
   ....:                   's': ['a', 'b', 'c', 'd']})
   ....: 

In [77]: right = DataFrame({'k': ['K1', 'K2', 'K4'],
   ....:                    'rv': [1, 2, 3]})
   ....: 

In [78]: result = ordered_merge(left, right, fill_method='ffill', left_by='s')
_images/merging_ordered_merge.png

Merging together values within Series or DataFrame columns

Another fairly common situation is to have two like-indexed (or similarly indexed) Series or DataFrame objects and wanting to “patch” values in one object from values for matching indices in the other. Here is an example:

In [79]: df1 = DataFrame([[nan, 3., 5.], [-4.6, np.nan, nan],
   ....:                  [nan, 7., nan]])
   ....: 

In [80]: df2 = DataFrame([[-42.6, np.nan, -8.2], [-5., 1.6, 4]],
   ....:                 index=[1, 2])
   ....: 

For this, use the combine_first method:

In [81]: result = df1.combine_first(df2)
_images/merging_combine_first.png

Note that this method only takes values from the right DataFrame if they are missing in the left DataFrame. A related method, update, alters non-NA values inplace:

In [82]: df1.update(df2)
_images/merging_update.png