bpd.DataFrame.merge

DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False)[source]

Merge DataFrame or named Series objects with a database-style join.

The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on.

Parameters:
  • right (DataFrame or named Series) – Object to merge with.
  • how ({'left', 'right', 'outer', 'inner'}, default 'inner') –

    Type of merge to be performed.

    * left: use only keys from left frame, similar to a SQL left outer
    join; preserve key order.
    * right: use only keys from right frame, similar to a SQL right
    outer join; preserve key order.
    * outer: use union of keys from both frames, similar to a SQL full
    outer join; sort keys lexicographically.
    * inner: use intersection of keys from both frames, similar to a
    SQL inner join; preserve the order of the left keys.
  • on (label or list) – Column or index level names to join on. These must be found in both DataFrames. If on is None and not merging on indexes then this defaults to the intersection of the columns in both DataFrames.
  • left_on (label or list, or array-like) – Column or index level names to join on in the left DataFrame. Can also be an array or list of arrays of the length of the left DataFrame. These arrays are treated as if they are columns.
  • right_on (label or list, or array-like) –
    Column or index level names to join on in the right DataFrame. Can
    also be an array or list of arrays of the length of the right
    left_index : boolean, default False
    Use the index from the left DataFrame as the join key(s). If it is a MultiIndex, the number of keys in the other DataFrame (either the index or a number of columns) must match the number of levels
  • right_index (boolean, default False) – Use the index from the right DataFrame as the join key. Same caveats as left_index DataFrame. These arrays are treated as if they are columns.
Returns:

A DataFrame of the two merged objects.

Return type:

DataFrame

Raises:

KeyError – If any input labels are not found in the corresponding DataFrame’s columns.

Examples

>>> df1 = bpd.DataFrame().assign(pet=['dog', 'cat', 'lizard', 'turtle'],
...                              kind=['mammal', 'mammal', 'reptile', 'reptile'])
>>> df2 = bpd.DataFrame().assign(kind=['mammal', 'reptile', 'amphibian'],
...                              abr=['m', 'r', 'a'])
>>> df1.merge(df2, on='kind')
      pet     kind abr
0     dog   mammal   m
1     cat   mammal   m
2  lizard  reptile   r
3  turtle  reptile   r