Merge, join, and concatenate

pandas provides various facilities for easily combining together Series orDataFrame with various kinds of set logic for the indexesand relational algebra functionality in the case of join / merge-typeoperations.

Concatenating objects

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

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

  1. In [1]: df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
  2. ...: 'B': ['B0', 'B1', 'B2', 'B3'],
  3. ...: 'C': ['C0', 'C1', 'C2', 'C3'],
  4. ...: 'D': ['D0', 'D1', 'D2', 'D3']},
  5. ...: index=[0, 1, 2, 3])
  6. ...:
  7.  
  8. In [2]: df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],
  9. ...: 'B': ['B4', 'B5', 'B6', 'B7'],
  10. ...: 'C': ['C4', 'C5', 'C6', 'C7'],
  11. ...: 'D': ['D4', 'D5', 'D6', 'D7']},
  12. ...: index=[4, 5, 6, 7])
  13. ...:
  14.  
  15. In [3]: df3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],
  16. ...: 'B': ['B8', 'B9', 'B10', 'B11'],
  17. ...: 'C': ['C8', 'C9', 'C10', 'C11'],
  18. ...: 'D': ['D8', 'D9', 'D10', 'D11']},
  19. ...: index=[8, 9, 10, 11])
  20. ...:
  21.  
  22. In [4]: frames = [df1, df2, df3]
  23.  
  24. In [5]: result = pd.concat(frames)
  1.  

../_images/merging_concat_basic.pngLike its sibling function on ndarrays, numpy.concatenate, pandas.concattakes a list or dict of homogeneously-typed objects and concatenates them withsome configurable handling of “what to do with the other axes”:

  1. pd.concat(objs, axis=0, join='outer', ignore_index=False, keys=None,
  2. levels=None, names=None, verify_integrity=False, copy=True)
  • objs : a sequence or mapping of Series or DataFrame objects. If adict is passed, the sorted keys will be used as the keys argument, unlessit is passed, in which case the values will be selected (see below). Any Noneobjects will be dropped silently unless they are all None in which case aValueError will be raised.
  • axis : {0, 1, …}, default 0. The axis to concatenate along.
  • join : {‘inner’, ‘outer’}, default ‘outer’. How to handle indexes onother axis(es). Outer for union and inner for intersection.
  • ignore_index : boolean, default False. If True, do not use the indexvalues on the concatenation axis. The resulting axis will be labeled 0, …,n - 1. This is useful if you are concatenating objects where theconcatenation axis does not have meaningful indexing information. Notethe index values on the other axes are still respected in the join.
  • keys : sequence, default None. Construct hierarchical index using thepassed keys as the outermost level. If multiple levels passed, shouldcontain tuples.
  • levels : list of sequences, default None. Specific levels (unique values)to use for constructing a MultiIndex. Otherwise they will be inferred from thekeys.
  • names : list, default None. Names for the levels in the resultinghierarchical index.
  • verify_integrity : boolean, default False. Check whether the newconcatenated axis contains duplicates. This can be very expensive relativeto the actual data concatenation.
  • copy : boolean, default True. If False, do not copy data unnecessarily.

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 keyswith each of the pieces of the chopped up DataFrame. We can do this using thekeys argument:

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

../_images/merging_concat_keys.pngAs you can see (if you’ve read the rest of the documentation), the resultingobject’s index has a hierarchical index. Thismeans that we can now select out each chunk by key:

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

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

Note

It is worth noting that concat() (and thereforeappend()) makes a full copy of the data, and that constantlyreusing this function can create a significant performance hit. If you needto use the operation over several datasets, use a list comprehension.

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

Set logic on the other axes

When gluing together multiple DataFrames, you have a choice of how to handlethe other axes (other than the one being concatenated). This can be done inthe following two ways:

  • Take the union of them all, join='outer'. This is the defaultoption as it results in zero information loss.
  • Take the intersection, join='inner'.

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

  1. In [8]: df4 = pd.DataFrame({'B': ['B2', 'B3', 'B6', 'B7'],
  2. ...: 'D': ['D2', 'D3', 'D6', 'D7'],
  3. ...: 'F': ['F2', 'F3', 'F6', 'F7']},
  4. ...: index=[2, 3, 6, 7])
  5. ...:
  6.  
  7. In [9]: result = pd.concat([df1, df4], axis=1, sort=False)
  1.  

../_images/merging_concat_axis1.png

Warning

Changed in version 0.23.0.

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

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

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

../_images/merging_concat_axis1_inner.pngLastly, suppose we just wanted to reuse the exact index from the originalDataFrame:

  1. In [11]: result = pd.concat([df1, df4], axis=1).reindex(df1.index)

Similarly, we could index before the concatenation:

  1. In [12]: pd.concat([df1, df4.reindex(df1.index)], axis=1)
  2. Out[12]:
  3. A B C D B D F
  4. 0 A0 B0 C0 D0 NaN NaN NaN
  5. 1 A1 B1 C1 D1 NaN NaN NaN
  6. 2 A2 B2 C2 D2 B2 D2 F2
  7. 3 A3 B3 C3 D3 B3 D3 F3
  1.  

../_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 predatedconcat. They concatenate along axis=0, namely the index:

  1. In [13]: result = df1.append(df2)
  1.  

../_images/merging_append1.pngIn the case of DataFrame, the indexes must be disjoint but the columns do notneed to be:

  1. In [14]: result = df1.append(df4, sort=False)
  1.  

../_images/merging_append2.pngappend may take multiple objects to concatenate:

  1. In [15]: result = df1.append([df2, df3])
  1.  

../_images/merging_append3.png

Note

Unlike the append() method, which appends to the original listand returns None, append() here does not modifydf1 and returns its copy with df2 appended.

Ignoring indexes on the concatenation axis

For DataFrame objects which don’t have a meaningful index, you may wishto append them and ignore the fact that they may have overlapping indexes. Todo this, use the ignore_index argument:

  1. In [16]: result = pd.concat([df1, df4], ignore_index=True, sort=False)
  1.  

../_images/merging_concat_ignore_index.pngThis is also a valid argument to DataFrame.append():

  1. In [17]: result = df1.append(df4, ignore_index=True, sort=False)
  1.  

../_images/merging_append_ignore_index.png

Concatenating with mixed ndims

You can concatenate a mix of Series and DataFrame objects. TheSeries will be transformed to DataFrame with the column name asthe name of the Series.

  1. In [18]: s1 = pd.Series(['X0', 'X1', 'X2', 'X3'], name='X')
  2.  
  3. In [19]: result = pd.concat([df1, s1], axis=1)
  1.  

../_images/merging_concat_mixed_ndim.png

Note

Since we’re concatenating a Series to a DataFrame, we could haveachieved the same result with DataFrame.assign(). To concatenate anarbitrary number of pandas objects (DataFrame or Series), useconcat.

If unnamed Series are passed they will be numbered consecutively.

  1. In [20]: s2 = pd.Series(['_0', '_1', '_2', '_3'])
  2.  
  3. In [21]: result = pd.concat([df1, s2, s2, s2], axis=1)
  1.  

../_images/merging_concat_unnamed_series.pngPassing ignore_index=True will drop all name references.

  1. In [22]: result = pd.concat([df1, s1], axis=1, ignore_index=True)
  1.  

../_images/merging_concat_series_ignore_index.png

More concatenating with group keys

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

  1. In [23]: s3 = pd.Series([0, 1, 2, 3], name='foo')
  2.  
  3. In [24]: s4 = pd.Series([0, 1, 2, 3])
  4.  
  5. In [25]: s5 = pd.Series([0, 1, 4, 5])
  6.  
  7. In [26]: pd.concat([s3, s4, s5], axis=1)
  8. Out[26]:
  9. foo 0 1
  10. 0 0 0 0
  11. 1 1 1 1
  12. 2 2 2 4
  13. 3 3 3 5

Through the keys argument we can override the existing column names.

  1. In [27]: pd.concat([s3, s4, s5], axis=1, keys=['red', 'blue', 'yellow'])
  2. Out[27]:
  3. red blue yellow
  4. 0 0 0 0
  5. 1 1 1 1
  6. 2 2 2 4
  7. 3 3 3 5

Let’s consider a variation of the very first example presented:

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

../_images/merging_concat_group_keys2.pngYou can also pass a dict to concat in which case the dict keys will be usedfor the keys argument (unless other keys are specified):

  1. In [29]: pieces = {'x': df1, 'y': df2, 'z': df3}
  2.  
  3. In [30]: result = pd.concat(pieces)
  1.  

../_images/merging_concat_dict.png

  1. In [31]: result = pd.concat(pieces, keys=['z', 'y'])
  1.  

../_images/merging_concat_dict_keys.pngThe MultiIndex created has levels that are constructed from the passed keys andthe index of the DataFrame pieces:

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

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

  1. In [33]: result = pd.concat(pieces, keys=['x', 'y', 'z'],
  2. ....: levels=[['z', 'y', 'x', 'w']],
  3. ....: names=['group_key'])
  4. ....:
  1.  

../_images/merging_concat_dict_keys_names.png

  1. In [34]: result.index.levels
  2. Out[34]: FrozenList([['z', 'y', 'x', 'w'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

This is fairly esoteric, but it is actually necessary for implementing thingslike 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 canappend a single row to a DataFrame by passing a Series or dict toappend, which returns a new DataFrame as above.

  1. In [35]: s2 = pd.Series(['X0', 'X1', 'X2', 'X3'], index=['A', 'B', 'C', 'D'])
  2.  
  3. In [36]: result = df1.append(s2, ignore_index=True)
  1.  

../_images/merging_append_series_as_row.pngYou should use ignore_index with this method to instruct DataFrame todiscard its index. If you wish to preserve the index, you should construct anappropriately-indexed DataFrame and append or concatenate those objects.

You can also pass a list of dicts or Series:

  1. In [37]: dicts = [{'A': 1, 'B': 2, 'C': 3, 'X': 4},
  2. ....: {'A': 5, 'B': 6, 'C': 7, 'Y': 8}]
  3. ....:
  4.  
  5. In [38]: result = df1.append(dicts, ignore_index=True, sort=False)
  1.  

../_images/merging_append_dits.png

Database-style DataFrame or named Series joining/merging

pandas has full-featured, high performance in-memory join operationsidiomatically very similar to relational databases like SQL. These methodsperform significantly better (in some cases well over an order of magnitudebetter) than other open source implementations (like base::merge.data.framein R). The reason for this is careful algorithmic design and the internal layoutof 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 acomparison with SQL.

pandas provides a single function, merge(), as the entry point forall standard database join operations between DataFrame or named Series objects:

  1. pd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,
  2. left_index=False, right_index=False, sort=True,
  3. suffixes=('_x', '_y'), copy=True, indicator=False,
  4. validate=None)
  • left: A DataFrame or named Series object.

  • right: Another DataFrame or named Series object.

  • on: Column or index level names to join on. Must be found in both the leftand right DataFrame and/or Series objects. If not passed and left_index andright_index are False, the intersection of the columns in theDataFrames and/or Series will be inferred to be the join keys.

  • left_on: Columns or index levels from the left DataFrame or Series to use askeys. Can either be column names, index level names, or arrays with lengthequal to the length of the DataFrame or Series.

  • right_on: Columns or index levels from the right DataFrame or Series to use askeys. Can either be column names, index level names, or arrays with lengthequal to the length of the DataFrame or Series.

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

  • right_index: Same usage as left_index for the right DataFrame or Series

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

  • sort: Sort the result DataFrame by the join keys in lexicographicalorder. Defaults to True, setting to False will improve performancesubstantially in many cases.

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

  • copy: Always copy data (default True) from the passed DataFrame or named Seriesobjects, even when reindexing is not necessary. Cannot be avoided in manycases but may improve performance / memory usage. The cases where copyingcan be avoided are somewhat pathological but this option is providednonetheless.

  • indicator: Add a column to the output DataFrame called _mergewith information on the source of each row. _merge is Categorical-typeand takes on a value of left_only for observations whose merge keyonly appears in 'left' DataFrame or Series, right_only for observations whosemerge key only appears in 'right' DataFrame or Series, and both if theobservation’s merge key is found in both.

  • validate : string, default None.If specified, checks if merge is of specified type.

  • “one_to_one” or “1:1”: checks if merge keys are unique in bothleft and right datasets.
  • “one_to_many” or “1:m”: checks if merge keys are unique in leftdataset.
  • “many_to_one” or “m:1”: checks if merge keys are unique in rightdataset.
  • “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, andright_on parameters was added in version 0.23.0.Support for merging named Series objects was added in version 0.24.0.

The return type will be the same as left. If left is a DataFrame or named Seriesand 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 aDataFrame instance method merge(), with the callingDataFrame being implicitly considered the left object in the join.

The related join() method, uses merge internally for theindex-on-index (by default) and column(s)-on-index join. If you are joining onindex only, 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 theterminology used to describe join operations between two SQL-table likestructures (DataFrame objects). There are several cases to consider whichare very important to understand:

  • one-to-one joins: for example when joining two DataFrame objects ontheir indexes (which must contain unique values).
  • many-to-one joins: for example when joining an index (unique) to one ormore 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), anyindexes on the passed DataFrame objects will be discarded.

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

  1. In [39]: left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
  2. ....: 'A': ['A0', 'A1', 'A2', 'A3'],
  3. ....: 'B': ['B0', 'B1', 'B2', 'B3']})
  4. ....:
  5.  
  6. In [40]: right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
  7. ....: 'C': ['C0', 'C1', 'C2', 'C3'],
  8. ....: 'D': ['D0', 'D1', 'D2', 'D3']})
  9. ....:
  10.  
  11. In [41]: result = pd.merge(left, right, on='key')
  1.  

../_images/merging_merge_on_key.pngHere is a more complicated example with multiple join keys. Only the keysappearing in left and right are present (the intersection), sincehow='inner' by default.

  1. In [42]: left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
  2. ....: 'key2': ['K0', 'K1', 'K0', 'K1'],
  3. ....: 'A': ['A0', 'A1', 'A2', 'A3'],
  4. ....: 'B': ['B0', 'B1', 'B2', 'B3']})
  5. ....:
  6.  
  7. In [43]: right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
  8. ....: 'key2': ['K0', 'K0', 'K0', 'K0'],
  9. ....: 'C': ['C0', 'C1', 'C2', 'C3'],
  10. ....: 'D': ['D0', 'D1', 'D2', 'D3']})
  11. ....:
  12.  
  13. In [44]: result = pd.merge(left, right, on=['key1', 'key2'])
  1.  

../_images/merging_merge_on_key_multiple.pngThe how argument to merge specifies how to determine which keys are tobe included in the resulting table. If a key combination does not appear ineither the left or right tables, the values in the joined table will beNA. Here is a summary of the how options and their SQL equivalent names:

Merge methodSQL Join NameDescription
leftLEFT OUTER JOINUse keys from left frame only
rightRIGHT OUTER JOINUse keys from right frame only
outerFULL OUTER JOINUse union of keys from both frames
innerINNER JOINUse intersection of keys from both frames
  1. In [45]: result = pd.merge(left, right, how='left', on=['key1', 'key2'])
  1.  

../_images/merging_merge_on_key_left.png

  1. In [46]: result = pd.merge(left, right, how='right', on=['key1', 'key2'])
  1.  

../_images/merging_merge_on_key_right.png

  1. In [47]: result = pd.merge(left, right, how='outer', on=['key1', 'key2'])
  1.  

../_images/merging_merge_on_key_outer.png

  1. In [48]: result = pd.merge(left, right, how='inner', on=['key1', 'key2'])
  1.  

../_images/merging_merge_on_key_inner.pngHere is another example with duplicate join keys in DataFrames:

  1. In [49]: left = pd.DataFrame({'A': [1, 2], 'B': [2, 2]})
  2.  
  3. In [50]: right = pd.DataFrame({'A': [4, 5, 6], 'B': [2, 2, 2]})
  4.  
  5. In [51]: result = pd.merge(left, right, on='B', how='outer')
  1.  

../_images/merging_merge_on_key_dup.png

Warning

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.

Checking for duplicate keys

New in version 0.21.0.

Users can use the validate argument to automatically check whether thereare unexpected duplicates in their merge keys. Key uniqueness is checked beforemerge operations and so should protect against memory overflows. Checking keyuniqueness 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 rightDataFrame. As this is not a one-to-one merge – as specified in thevalidate argument – an exception will be raised.

  1. In [52]: left = pd.DataFrame({'A' : [1,2], 'B' : [1, 2]})
  2.  
  3. In [53]: right = pd.DataFrame({'A' : [4,5,6], 'B': [2, 2, 2]})
  1. In [53]: result = pd.merge(left, right, on='B', how='outer', validate="one_to_one")
  2. ...
  3. 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 toensure there are no duplicates in the left DataFrame, one can use thevalidate='one_to_many' argument instead, which will not raise an exception.

  1. In [54]: pd.merge(left, right, on='B', how='outer', validate="one_to_many")
  2. Out[54]:
  3. A_x B A_y
  4. 0 1 1 NaN
  5. 1 2 2 4.0
  6. 2 2 2 5.0
  7. 3 2 2 6.0

The merge indicator

merge() accepts the argument indicator. If True, aCategorical-type column called _merge will be added to the output objectthat takes on values:

Observation Origin_merge value
Merge key only in 'left' frameleft_only
Merge key only in 'right' frameright_only
Merge key in both framesboth
  1. In [55]: df1 = pd.DataFrame({'col1': [0, 1], 'col_left': ['a', 'b']})
  2.  
  3. In [56]: df2 = pd.DataFrame({'col1': [1, 2, 2], 'col_right': [2, 2, 2]})
  4.  
  5. In [57]: pd.merge(df1, df2, on='col1', how='outer', indicator=True)
  6. Out[57]:
  7. col1 col_left col_right _merge
  8. 0 0 a NaN left_only
  9. 1 1 b 2.0 both
  10. 2 2 NaN 2.0 right_only
  11. 3 2 NaN 2.0 right_only

The indicator argument will also accept string arguments, in which case the indicator function will use the value of the passed string as the name for the indicator column.

  1. In [58]: pd.merge(df1, df2, on='col1', how='outer', indicator='indicator_column')
  2. Out[58]:
  3. col1 col_left col_right indicator_column
  4. 0 0 a NaN left_only
  5. 1 1 b 2.0 both
  6. 2 2 NaN 2.0 right_only
  7. 3 2 NaN 2.0 right_only

Merge dtypes

New in version 0.19.0.

Merging will preserve the dtype of the join keys.

  1. In [59]: left = pd.DataFrame({'key': [1], 'v1': [10]})
  2.  
  3. In [60]: left
  4. Out[60]:
  5. key v1
  6. 0 1 10
  7.  
  8. In [61]: right = pd.DataFrame({'key': [1, 2], 'v1': [20, 30]})
  9.  
  10. In [62]: right
  11. Out[62]:
  12. key v1
  13. 0 1 20
  14. 1 2 30

We are able to preserve the join keys:

  1. In [63]: pd.merge(left, right, how='outer')
  2. Out[63]:
  3. key v1
  4. 0 1 10
  5. 1 1 20
  6. 2 2 30
  7.  
  8. In [64]: pd.merge(left, right, how='outer').dtypes
  9. Out[64]:
  10. key int64
  11. v1 int64
  12. dtype: object

Of course if you have missing values that are introduced, then theresulting dtype will be upcast.

  1. In [65]: pd.merge(left, right, how='outer', on='key')
  2. Out[65]:
  3. key v1_x v1_y
  4. 0 1 10.0 20
  5. 1 2 NaN 30
  6.  
  7. In [66]: pd.merge(left, right, how='outer', on='key').dtypes
  8. Out[66]:
  9. key int64
  10. v1_x float64
  11. v1_y int64
  12. dtype: object

New in version 0.20.0.

Merging will preserve category dtypes of the mergands. See also the section on categoricals.

The left frame.

  1. In [67]: from pandas.api.types import CategoricalDtype
  2.  
  3. In [68]: X = pd.Series(np.random.choice(['foo', 'bar'], size=(10,)))
  4.  
  5. In [69]: X = X.astype(CategoricalDtype(categories=['foo', 'bar']))
  6.  
  7. In [70]: left = pd.DataFrame({'X': X,
  8. ....: 'Y': np.random.choice(['one', 'two', 'three'],
  9. ....: size=(10,))})
  10. ....:
  11.  
  12. In [71]: left
  13. Out[71]:
  14. X Y
  15. 0 bar one
  16. 1 foo one
  17. 2 foo three
  18. 3 bar three
  19. 4 foo one
  20. 5 bar one
  21. 6 bar three
  22. 7 bar three
  23. 8 bar three
  24. 9 foo three
  25.  
  26. In [72]: left.dtypes
  27. Out[72]:
  28. X category
  29. Y object
  30. dtype: object

The right frame.

  1. In [73]: right = pd.DataFrame({'X': pd.Series(['foo', 'bar'],
  2. ....: dtype=CategoricalDtype(['foo', 'bar'])),
  3. ....: 'Z': [1, 2]})
  4. ....:
  5.  
  6. In [74]: right
  7. Out[74]:
  8. X Z
  9. 0 foo 1
  10. 1 bar 2
  11.  
  12. In [75]: right.dtypes
  13. Out[75]:
  14. X category
  15. Z int64
  16. dtype: object

The merged result:

  1. In [76]: result = pd.merge(left, right, how='outer')
  2.  
  3. In [77]: result
  4. Out[77]:
  5. X Y Z
  6. 0 bar one 2
  7. 1 bar three 2
  8. 2 bar one 2
  9. 3 bar three 2
  10. 4 bar three 2
  11. 5 bar three 2
  12. 6 foo one 1
  13. 7 foo three 1
  14. 8 foo one 1
  15. 9 foo three 1
  16.  
  17. In [78]: result.dtypes
  18. Out[78]:
  19. X category
  20. Y object
  21. Z int64
  22. dtype: object

Note

The category dtypes must be exactly the same, meaning the same categories and the ordered attribute.Otherwise the result will coerce to object dtype.

Note

Merging on category dtypes that are the same can be quite performant compared to object dtype merging.

Joining on index

DataFrame.join() is a convenient method for combining the columns of twopotentially differently-indexed DataFrames into a single resultDataFrame. Here is a very basic example:

  1. In [79]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
  2. ....: 'B': ['B0', 'B1', 'B2']},
  3. ....: index=['K0', 'K1', 'K2'])
  4. ....:
  5.  
  6. In [80]: right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
  7. ....: 'D': ['D0', 'D2', 'D3']},
  8. ....: index=['K0', 'K2', 'K3'])
  9. ....:
  10.  
  11. In [81]: result = left.join(right)
  1.  

../_images/merging_join.png

  1. In [82]: result = left.join(right, how='outer')
  1.  

../_images/merging_join_outer.pngThe same as above, but with how='inner'.

  1. In [83]: result = left.join(right, how='inner')
  1.  

../_images/merging_join_inner.pngThe data alignment here is on the indexes (row labels). This same behavior canbe achieved using merge plus additional arguments instructing it to use theindexes:

  1. In [84]: result = pd.merge(left, right, left_index=True, right_index=True, how='outer')
  1.  

../_images/merging_merge_index_outer.png

  1. In [85]: result = pd.merge(left, right, left_index=True, right_index=True, how='inner');
  1.  

../_images/merging_merge_index_inner.png

Joining key columns on an index

join() takes an optional on argument which may be a columnor multiple column names, which specifies that the passed DataFrame is to bealigned on that column in the DataFrame. These two function calls arecompletely equivalent:

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

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

  1. In [86]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
  2. ....: 'B': ['B0', 'B1', 'B2', 'B3'],
  3. ....: 'key': ['K0', 'K1', 'K0', 'K1']})
  4. ....:
  5.  
  6. In [87]: right = pd.DataFrame({'C': ['C0', 'C1'],
  7. ....: 'D': ['D0', 'D1']},
  8. ....: index=['K0', 'K1'])
  9. ....:
  10.  
  11. In [88]: result = left.join(right, on='key')
  1.  

../_images/merging_join_key_columns.png

  1. In [89]: result = pd.merge(left, right, left_on='key', right_index=True,
  2. ....: how='left', sort=False);
  3. ....:
  1.  

../_images/merging_merge_key_columns.pngTo join on multiple keys, the passed DataFrame must have a MultiIndex:

  1. In [90]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
  2. ....: 'B': ['B0', 'B1', 'B2', 'B3'],
  3. ....: 'key1': ['K0', 'K0', 'K1', 'K2'],
  4. ....: 'key2': ['K0', 'K1', 'K0', 'K1']})
  5. ....:
  6.  
  7. In [91]: index = pd.MultiIndex.from_tuples([('K0', 'K0'), ('K1', 'K0'),
  8. ....: ('K2', 'K0'), ('K2', 'K1')])
  9. ....:
  10.  
  11. In [92]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
  12. ....: 'D': ['D0', 'D1', 'D2', 'D3']},
  13. ....: index=index)
  14. ....:

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

  1. In [93]: result = left.join(right, on=['key1', 'key2'])
  1.  

../_images/merging_join_multikeys.pngThe default for DataFrame.join is to perform a left join (essentially a“VLOOKUP” operation, for Excel users), which uses only the keys found in thecalling DataFrame. Other join types, for example inner join, can be just aseasily performed:

  1. In [94]: result = left.join(right, on=['key1', 'key2'], how='inner')
  1.  

../_images/merging_join_multikeys_inner.pngAs you can see, this drops any rows where there was no match.

Joining a single Index to a MultiIndex

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

  1. In [95]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
  2. ....: 'B': ['B0', 'B1', 'B2']},
  3. ....: index=pd.Index(['K0', 'K1', 'K2'], name='key'))
  4. ....:
  5.  
  6. In [96]: index = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
  7. ....: ('K2', 'Y2'), ('K2', 'Y3')],
  8. ....: names=['key', 'Y'])
  9. ....:
  10.  
  11. In [97]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
  12. ....: 'D': ['D0', 'D1', 'D2', 'D3']},
  13. ....: index=index)
  14. ....:
  15.  
  16. In [98]: result = left.join(right, how='inner')
  1.  

../_images/merging_join_multiindex_inner.pngThis is equivalent but less verbose and more memory efficient / faster than this.

  1. In [99]: result = pd.merge(left.reset_index(), right.reset_index(),
  2. ....: on=['key'], how='inner').set_index(['key','Y'])
  3. ....:
  1.  

../_images/merging_merge_multiindex_alternative.png

Joining with two MultiIndexes

This is supported in a limited way, provided that the index for the rightargument is completely used in the join, and is a subset of the indices inthe left argument, as in this example:

  1. In [100]: leftindex = pd.MultiIndex.from_product([list('abc'), list('xy'), [1, 2]],
  2. .....: names=['abc', 'xy', 'num'])
  3. .....:
  4.  
  5. In [101]: left = pd.DataFrame({'v1': range(12)}, index=leftindex)
  6.  
  7. In [102]: left
  8. Out[102]:
  9. v1
  10. abc xy num
  11. a x 1 0
  12. 2 1
  13. y 1 2
  14. 2 3
  15. b x 1 4
  16. 2 5
  17. y 1 6
  18. 2 7
  19. c x 1 8
  20. 2 9
  21. y 1 10
  22. 2 11
  23.  
  24. In [103]: rightindex = pd.MultiIndex.from_product([list('abc'), list('xy')],
  25. .....: names=['abc', 'xy'])
  26. .....:
  27.  
  28. In [104]: right = pd.DataFrame({'v2': [100 * i for i in range(1, 7)]}, index=rightindex)
  29.  
  30. In [105]: right
  31. Out[105]:
  32. v2
  33. abc xy
  34. a x 100
  35. y 200
  36. b x 300
  37. y 400
  38. c x 500
  39. y 600
  40.  
  41. In [106]: left.join(right, on=['abc', 'xy'], how='inner')
  42. Out[106]:
  43. v1 v2
  44. abc xy num
  45. a x 1 0 100
  46. 2 1 100
  47. y 1 2 200
  48. 2 3 200
  49. b x 1 4 300
  50. 2 5 300
  51. y 1 6 400
  52. 2 7 400
  53. c x 1 8 500
  54. 2 9 500
  55. y 1 10 600
  56. 2 11 600

If that condition is not satisfied, a join with two multi-indexes can bedone using the following code.

  1. In [107]: leftindex = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'),
  2. .....: ('K1', 'X2')],
  3. .....: names=['key', 'X'])
  4. .....:
  5.  
  6. In [108]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
  7. .....: 'B': ['B0', 'B1', 'B2']},
  8. .....: index=leftindex)
  9. .....:
  10.  
  11. In [109]: rightindex = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
  12. .....: ('K2', 'Y2'), ('K2', 'Y3')],
  13. .....: names=['key', 'Y'])
  14. .....:
  15.  
  16. In [110]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
  17. .....: 'D': ['D0', 'D1', 'D2', 'D3']},
  18. .....: index=rightindex)
  19. .....:
  20.  
  21. In [111]: result = pd.merge(left.reset_index(), right.reset_index(),
  22. .....: on=['key'], how='inner').set_index(['key', 'X', 'Y'])
  23. .....:
  1.  

../_images/merging_merge_two_multiindex.png

Merging on a combination of columns and index levels

New in version 0.23.

Strings passed as the on, left_on, and right_on parametersmay refer to either column names or index level names. This enables mergingDataFrame instances on a combination of index levels and columns withoutresetting indexes.

  1. In [112]: left_index = pd.Index(['K0', 'K0', 'K1', 'K2'], name='key1')
  2.  
  3. In [113]: left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
  4. .....: 'B': ['B0', 'B1', 'B2', 'B3'],
  5. .....: 'key2': ['K0', 'K1', 'K0', 'K1']},
  6. .....: index=left_index)
  7. .....:
  8.  
  9. In [114]: right_index = pd.Index(['K0', 'K1', 'K2', 'K2'], name='key1')
  10.  
  11. In [115]: right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
  12. .....: 'D': ['D0', 'D1', 'D2', 'D3'],
  13. .....: 'key2': ['K0', 'K0', 'K0', 'K1']},
  14. .....: index=right_index)
  15. .....:
  16.  
  17. In [116]: result = left.merge(right, on=['key1', 'key2'])
  1.  

../_images/merge_on_index_and_column.png

Note

When DataFrames are merged on a string that matches an index level in bothframes, the index level is preserved as an index level in the resultingDataFrame.

Note

When DataFrames are merged using only some of the levels of a MultiIndex,the extra levels will be dropped from the resulting merge. In order topreserve those levels, use reset_index on those level names to movethose levels to columns prior to doing the merge.

Note

If a string matches both a column name and an index level name, then awarning is issued and the column takes precedence. This will result in anambiguity error in a future version.

Overlapping value columns

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

  1. In [117]: left = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'v': [1, 2, 3]})
  2.  
  3. In [118]: right = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'v': [4, 5, 6]})
  4.  
  5. In [119]: result = pd.merge(left, right, on='k')
  1.  

../_images/merging_merge_overlapped.png

  1. In [120]: result = pd.merge(left, right, on='k', suffixes=['_l', '_r'])
  1.  

../_images/merging_merge_overlapped_suffix.pngDataFrame.join() has lsuffix and rsuffix arguments which behavesimilarly.

  1. In [121]: left = left.set_index('k')
  2.  
  3. In [122]: right = right.set_index('k')
  4.  
  5. In [123]: result = left.join(right, lsuffix='_l', rsuffix='_r')
  1.  

../_images/merging_merge_overlapped_multi_suffix.png

Joining multiple DataFrames

A list or tuple of DataFrames can also be passed to join()to join them together on their indexes.

  1. In [124]: right2 = pd.DataFrame({'v': [7, 8, 9]}, index=['K1', 'K1', 'K2'])
  2.  
  3. In [125]: result = left.join([right, right2])
  1.  

../_images/merging_join_multi_df.png

Merging together values within Series or DataFrame columns

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

  1. In [126]: df1 = pd.DataFrame([[np.nan, 3., 5.], [-4.6, np.nan, np.nan],
  2. .....: [np.nan, 7., np.nan]])
  3. .....:
  4.  
  5. In [127]: df2 = pd.DataFrame([[-42.6, np.nan, -8.2], [-5., 1.6, 4]],
  6. .....: index=[1, 2])
  7. .....:

For this, use the combine_first() method:

  1. In [128]: result = df1.combine_first(df2)
  1.  

../_images/merging_combine_first.pngNote that this method only takes values from the right DataFrame if they aremissing in the left DataFrame. A related method, update(),alters non-NA values in place:

  1. In [129]: df1.update(df2)
  1.  

../_images/merging_update.png

Timeseries friendly merging

Merging ordered data

A merge_ordered() function allows combining time series and otherordered data. In particular it has an optional fill_method keyword tofill/interpolate missing data:

  1. In [130]: left = pd.DataFrame({'k': ['K0', 'K1', 'K1', 'K2'],
  2. .....: 'lv': [1, 2, 3, 4],
  3. .....: 's': ['a', 'b', 'c', 'd']})
  4. .....:
  5.  
  6. In [131]: right = pd.DataFrame({'k': ['K1', 'K2', 'K4'],
  7. .....: 'rv': [1, 2, 3]})
  8. .....:
  9.  
  10. In [132]: pd.merge_ordered(left, right, fill_method='ffill', left_by='s')
  11. Out[132]:
  12. k lv s rv
  13. 0 K0 1.0 a NaN
  14. 1 K1 1.0 a 1.0
  15. 2 K2 1.0 a 2.0
  16. 3 K4 1.0 a 3.0
  17. 4 K1 2.0 b 1.0
  18. 5 K2 2.0 b 2.0
  19. 6 K4 2.0 b 3.0
  20. 7 K1 3.0 c 1.0
  21. 8 K2 3.0 c 2.0
  22. 9 K4 3.0 c 3.0
  23. 10 K1 NaN d 1.0
  24. 11 K2 4.0 d 2.0
  25. 12 K4 4.0 d 3.0

Merging asof

New in version 0.19.0.

A merge_asof() is similar to an ordered left-join except that we match onnearest key rather than equal keys. For each row in the left DataFrame,we select the last row in the right DataFrame whose on key is lessthan the left’s key. Both DataFrames must be sorted by the key.

Optionally an asof merge can perform a group-wise merge. This matches theby key equally, in addition to the nearest match on the on key.

For example; we might have trades and quotes and we want to asofmerge them.

  1. In [133]: trades = pd.DataFrame({
  2. .....: 'time': pd.to_datetime(['20160525 13:30:00.023',
  3. .....: '20160525 13:30:00.038',
  4. .....: '20160525 13:30:00.048',
  5. .....: '20160525 13:30:00.048',
  6. .....: '20160525 13:30:00.048']),
  7. .....: 'ticker': ['MSFT', 'MSFT',
  8. .....: 'GOOG', 'GOOG', 'AAPL'],
  9. .....: 'price': [51.95, 51.95,
  10. .....: 720.77, 720.92, 98.00],
  11. .....: 'quantity': [75, 155,
  12. .....: 100, 100, 100]},
  13. .....: columns=['time', 'ticker', 'price', 'quantity'])
  14. .....:
  15.  
  16. In [134]: quotes = pd.DataFrame({
  17. .....: 'time': pd.to_datetime(['20160525 13:30:00.023',
  18. .....: '20160525 13:30:00.023',
  19. .....: '20160525 13:30:00.030',
  20. .....: '20160525 13:30:00.041',
  21. .....: '20160525 13:30:00.048',
  22. .....: '20160525 13:30:00.049',
  23. .....: '20160525 13:30:00.072',
  24. .....: '20160525 13:30:00.075']),
  25. .....: 'ticker': ['GOOG', 'MSFT', 'MSFT',
  26. .....: 'MSFT', 'GOOG', 'AAPL', 'GOOG',
  27. .....: 'MSFT'],
  28. .....: 'bid': [720.50, 51.95, 51.97, 51.99,
  29. .....: 720.50, 97.99, 720.50, 52.01],
  30. .....: 'ask': [720.93, 51.96, 51.98, 52.00,
  31. .....: 720.93, 98.01, 720.88, 52.03]},
  32. .....: columns=['time', 'ticker', 'bid', 'ask'])
  33. .....:
  1. In [135]: trades
  2. Out[135]:
  3. time ticker price quantity
  4. 0 2016-05-25 13:30:00.023 MSFT 51.95 75
  5. 1 2016-05-25 13:30:00.038 MSFT 51.95 155
  6. 2 2016-05-25 13:30:00.048 GOOG 720.77 100
  7. 3 2016-05-25 13:30:00.048 GOOG 720.92 100
  8. 4 2016-05-25 13:30:00.048 AAPL 98.00 100
  9.  
  10. In [136]: quotes
  11. Out[136]:
  12. time ticker bid ask
  13. 0 2016-05-25 13:30:00.023 GOOG 720.50 720.93
  14. 1 2016-05-25 13:30:00.023 MSFT 51.95 51.96
  15. 2 2016-05-25 13:30:00.030 MSFT 51.97 51.98
  16. 3 2016-05-25 13:30:00.041 MSFT 51.99 52.00
  17. 4 2016-05-25 13:30:00.048 GOOG 720.50 720.93
  18. 5 2016-05-25 13:30:00.049 AAPL 97.99 98.01
  19. 6 2016-05-25 13:30:00.072 GOOG 720.50 720.88
  20. 7 2016-05-25 13:30:00.075 MSFT 52.01 52.03

By default we are taking the asof of the quotes.

  1. In [137]: pd.merge_asof(trades, quotes,
  2. .....: on='time',
  3. .....: by='ticker')
  4. .....:
  5. Out[137]:
  6. time ticker price quantity bid ask
  7. 0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.96
  8. 1 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.98
  9. 2 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.93
  10. 3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93
  11. 4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN

We only asof within 2ms between the quote time and the trade time.

  1. In [138]: pd.merge_asof(trades, quotes,
  2. .....: on='time',
  3. .....: by='ticker',
  4. .....: tolerance=pd.Timedelta('2ms'))
  5. .....:
  6. Out[138]:
  7. time ticker price quantity bid ask
  8. 0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.96
  9. 1 2016-05-25 13:30:00.038 MSFT 51.95 155 NaN NaN
  10. 2 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.93
  11. 3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93
  12. 4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN

We only asof within 10ms between the quote time and the trade time and weexclude exact matches on time. Note that though we exclude the exact matches(of the quotes), prior quotes do propagate to that point in time.

  1. In [139]: pd.merge_asof(trades, quotes,
  2. .....: on='time',
  3. .....: by='ticker',
  4. .....: tolerance=pd.Timedelta('10ms'),
  5. .....: allow_exact_matches=False)
  6. .....:
  7. Out[139]:
  8. time ticker price quantity bid ask
  9. 0 2016-05-25 13:30:00.023 MSFT 51.95 75 NaN NaN
  10. 1 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.98
  11. 2 2016-05-25 13:30:00.048 GOOG 720.77 100 NaN NaN
  12. 3 2016-05-25 13:30:00.048 GOOG 720.92 100 NaN NaN
  13. 4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN