Merge, join, and concatenate
-
objs
: a sequence or mapping of Series or DataFrame 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. -
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. Specific levels (unique values)
to use for constructing a 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. -
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 keys
with each of the pieces of the chopped up DataFrame. We can do this using thekeys
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:
In [7]: result.loc[‘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 that concat()
(and thereforeappend()
) 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.
frames = [ process_your_file(f) for f in files ]
result = pd.concat(frames)
# Set logic on the other axes
When gluing together multiple DataFrames, you have a choice of how to handle
the other axes (other than the one being concatenated). This can be done in
the following two ways:
- Take the union of them all,
join=‘outer’
. This is the default
option 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:
In [8]: df4 = pd.DataFrame({‘B’: [‘B2’, ‘B3’, ‘B6’, ‘B7’],
...: ‘D’: [‘D2’, ‘D3’, ‘D6’, ‘D7’],
...: ‘F’: [‘F2’, ‘F3’, ‘F6’, ‘F7’]},
...: index=[2, 3, 6, 7])
...:
In [9]: result = pd.concat([df1, df4], axis=1, sort=False)
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 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:
In [11]: result = pd.concat([df1, df4], axis=1).reindex(df1.index)
Similarly, we could index before the concatenation:
In [12]: pd.concat([df1, df4.reindex(df1.index)], axis=1)
Out[12]:
A B C D B D F
0 A0 B0 C0 D0 NaN NaN NaN
1 A1 B1 C1 D1 NaN NaN NaN
2 A2 B2 C2 D2 B2 D2 F2
3 A3 B3 C3 D3 B3 D3 F3
# 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:
In [13]: result = df1.append(df2)
In the case of DataFrame
, the indexes must be disjoint but the columns do not
need to be:
In [14]: result = df1.append(df4, sort=False)
append
may take multiple objects to concatenate:
In [15]: result = df1.append([df2, df3])
Note
Unlike the append()
method, which appends to the original list
and 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 wish
to append them and ignore the fact that they may have overlapping indexes. To
do this, use the ignore_index
argument:
In [16]: result = pd.concat([df1, df4], ignore_index=True, sort=False)
This is also a valid argument to DataFrame.append()
:
In [17]: result = df1.append(df4, ignore_index=True, sort=False)
# Concatenating with mixed ndims
You can concatenate a mix of Series
and DataFrame
objects. TheSeries
will be transformed to DataFrame
with the column name as
the name of the Series
.
In [18]: s1 = pd.Series([‘X0’, ‘X1’, ‘X2’, ‘X3’], name=‘X’)
In [19]: result = pd.concat([df1, s1], axis=1)
Note
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
), useconcat
.
If unnamed Series
are passed they will be numbered consecutively.
In [20]: s2 = pd.Series([’_0’, ‘_1’, ‘_2’, ‘_3’])
In [21]: result = pd.concat([df1, s2, s2, s2], axis=1)
Passing ignore_index=True
will drop all name references.
In [22]: result = pd.concat([df1, s1], axis=1, ignore_index=True)
# More concatenating with group keys
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.
In [23]: s3 = pd.Series([0, 1, 2, 3], name=‘foo’)
In [24]: s4 = pd.Series([0, 1, 2, 3])
In [25]: s5 = pd.Series([0, 1, 4, 5])
In [26]: pd.concat([s3, s4, s5], axis=1)
Out[26]:
foo 0 1
0 0 0 0
1 1 1 1
2 2 2 4
3 3 3 5
Through the keys
argument we can override the existing column names.
In [27]: pd.concat([s3, s4, s5], axis=1, keys=[‘red’, ‘blue’, ‘yellow’])
Out[27]:
red blue yellow
0 0 0 0
1 1 1 1
2 2 2 4
3 3 3 5
Let’s consider a variation of the very first example presented:
In [28]: result = pd.concat(frames, keys=[‘x’, ‘y’, ‘z’])
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 [29]: pieces = {‘x’: df1, ‘y’: df2, ‘z’: df3}
In [30]: result = pd.concat(pieces)
In [31]: result = pd.concat(pieces, keys=[‘z’, ‘y’])
The MultiIndex created has levels that are constructed from the passed keys and
the index of the DataFrame
pieces:
In [32]: result.index.levels
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 can
do so using the levels
argument:
In [33]: result = pd.concat(pieces, keys=[‘x’, ‘y’, ‘z’],
....: levels=[[‘z’, ‘y’, ‘x’, ‘w’]],
....: names=[‘group_key’])
....:
In [34]: result.index.levels
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 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 toappend
, which returns a new DataFrame
as above.
In [35]: s2 = pd.Series([‘X0’, ‘X1’, ‘X2’, ‘X3’], index=[‘A’, ‘B’, ‘C’, ‘D’])
In [36]: result = df1.append(s2, ignore_index=True)
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 [37]: dicts = [{‘A’: 1, ‘B’: 2, ‘C’: 3, ‘X’: 4},
....: {‘A’: 5, ‘B’: 6, ‘C’: 7, ‘Y’: 8}]
....:
In [38]: result = df1.append(dicts, ignore_index=True, sort=False)
# Database-style DataFrame or named Series 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 the 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
or named Series
objects:
pd.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, indicator=False,
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 left
and right DataFrame and/or Series objects. If not passed andleft_index
andright_index
areFalse
, the intersection of the columns in the
DataFrames 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 as
keys. Can either be column names, index level names, or arrays with length
equal to the length of the DataFrame or Series.right_on
: Columns or index levels from the right DataFrame or Series to use as
keys. Can either be column names, index level names, or arrays with length
equal to the length of the DataFrame or Series.left_index
: IfTrue
, use the index (row labels) from the left
DataFrame 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 keys
from the right DataFrame or Series.right_index
: Same usage asleft_index
for the right DataFrame or Serieshow
: One of‘left’
,‘right’
,‘outer’
,‘inner’
. Defaults
toinner
. See below for more detailed description of each method.sort
: Sort the result DataFrame by the join keys in lexicographical
order. Defaults toTrue
, setting toFalse
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 (defaultTrue
) from the passed DataFrame or named Series
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 ofleft_only
for observations whose merge key
only appears in‘left’
DataFrame or Series,right_only
for observations whose
merge key only appears in‘right’
DataFrame or Series, andboth
if the
observation’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 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.
- “one_to_one” or “1:1”: checks if merge keys are unique in both
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 Series
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 aDataFrame
instance method merge()
, with the callingDataFrame
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.
# 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 differentDataFrame
. - 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 [39]: left = pd.DataFrame({‘key’: [‘K0’, ‘K1’, ‘K2’, ‘K3’],
....: ‘A’: [‘A0’, ‘A1’, ‘A2’, ‘A3’],
....: ‘B’: [‘B0’, ‘B1’, ‘B2’, ‘B3’]})
....:
In [40]: right = pd.DataFrame({‘key’: [‘K0’, ‘K1’, ‘K2’, ‘K3’],
....: ‘C’: [‘C0’, ‘C1’, ‘C2’, ‘C3’],
....: ‘D’: [‘D0’, ‘D1’, ‘D2’, ‘D3’]})
....:
In [41]: result = pd.merge(left, right, on=‘key’)
Here is a more complicated example with multiple join keys. Only the keys
appearing in left
and right
are present (the intersection), sincehow=‘inner’
by default.
In [42]: left = pd.DataFrame({‘key1’: [‘K0’, ‘K0’, ‘K1’, ‘K2’],
....: ‘key2’: [‘K0’, ‘K1’, ‘K0’, ‘K1’],
....: ‘A’: [‘A0’, ‘A1’, ‘A2’, ‘A3’],
....: ‘B’: [‘B0’, ‘B1’, ‘B2’, ‘B3’]})
....:
In [43]: right = pd.DataFrame({‘key1’: [‘K0’, ‘K1’, ‘K1’, ‘K2’],
....: ‘key2’: [‘K0’, ‘K0’, ‘K0’, ‘K0’],
....: ‘C’: [‘C0’, ‘C1’, ‘C2’, ‘C3’],
....: ‘D’: [‘D0’, ‘D1’, ‘D2’, ‘D3’]})
....:
In [44]: result = pd.merge(left, right, on=[‘key1’, ‘key2’])
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 beNA
. 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 [45]: result = pd.merge(left, right, how=‘left’, on=[‘key1’, ‘key2’])
In [46]: result = pd.merge(left, right, how=‘right’, on=[‘key1’, ‘key2’])
In [47]: result = pd.merge(left, right, how=‘outer’, on=[‘key1’, ‘key2’])
In [48]: result = pd.merge(left, right, how=‘inner’, on=[‘key1’, ‘key2’])
Here is another example with duplicate join keys in DataFrames:
In [49]: left = pd.DataFrame({‘A’: [1, 2], ‘B’: [2, 2]})
In [50]: right = pd.DataFrame({‘A’: [4, 5, 6], ‘B’: [2, 2, 2]})
In [51]: result = pd.merge(left, right, on=‘B’, how=‘outer’)
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 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 rightDataFrame
. As this is not a one-to-one merge – as specified in thevalidate
argument – an exception will be raised.
In [52]: left = pd.DataFrame({‘A’ : [1,2], ‘B’ : [1, 2]})
上一篇: 10_Android的消息机制
下一篇: Android Lottie动画使用