How to concatenate dataframes in python
pandas provides various facilities for easily combining together Series or DataFrame with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations. Show
In addition, pandas also provides utilities to compare two Series or DataFrame and summarize their differences. Concatenating objects¶The Before diving into all of the details of In [1]: df1 = pd.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 = pd.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 = pd.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 = pd.concat(frames) Like its sibling function on ndarrays, pd.concat( objs, axis=0, join="outer", ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True, )
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
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 frames = [ process_your_file(f) for f in files ] result = pd.concat(frames) Note When concatenating DataFrames with named axes, pandas will attempt to preserve these index/column names whenever possible. In the case where all inputs share a common name, this name will be assigned to the result. When the input names do not all agree, the result will be unnamed. The same is true for 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:
Here is an example of each of these methods. First, the default 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) Here is the same thing with 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 Ignoring indexes on the concatenation axis¶For In [13]: result = pd.concat([df1, df4], ignore_index=True, sort=False) Concatenating with mixed ndims¶You can concatenate a mix of In [14]: s1 = pd.Series(["X0", "X1", "X2", "X3"], name="X") In [15]: result = pd.concat([df1, s1], axis=1) Note Since we’re concatenating a If unnamed In [16]: s2 = pd.Series(["_0", "_1", "_2", "_3"]) In [17]: result = pd.concat([df1, s2, s2, s2], axis=1) Passing In [18]: result = pd.concat([df1, s1], axis=1, ignore_index=True) More concatenating with group keys¶A fairly common use
of the In [19]: s3 = pd.Series([0, 1, 2, 3], name="foo") In [20]: s4 = pd.Series([0, 1, 2, 3]) In [21]: s5 = pd.Series([0, 1, 4, 5]) In [22]: pd.concat([s3, s4, s5], axis=1) Out[22]: foo 0 1 0 0 0 0 1 1 1 1 2 2 2 4 3 3 3 5 Through the In [23]: pd.concat([s3, s4, s5], axis=1, keys=["red", "blue", "yellow"]) Out[23]: 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 [24]: result = pd.concat(frames, keys=["x", "y", "z"]) You can also pass a dict to In [25]: pieces = {"x": df1, "y": df2, "z": df3} In [26]: result = pd.concat(pieces) In [27]: result = pd.concat(pieces, keys=["z", "y"]) The MultiIndex created has levels that are constructed from the passed keys and the index of the In [28]: result.index.levels Out[28]: 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 In [29]: result = pd.concat( ....: pieces, keys=["x", "y", "z"], levels=[["z", "y", "x", "w"]], names=["group_key"] ....: ) ....: In [30]: result.index.levels Out[30]: 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¶If you have a series that you want to append as a single row to a In [31]: s2 = pd.Series(["X0", "X1", "X2", "X3"], index=["A", "B", "C", "D"]) In [32]: result = pd.concat([df1, s2.to_frame().T], ignore_index=True) You should use 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 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,
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, )
Note Support for specifying index levels as the The return type will be the same as
The
related 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 (
Note When joining columns on columns (potentially a many-to-many join), any indexes on the passed 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 = pd.DataFrame( ....: { ....: "key": ["K0", "K1", "K2", "K3"], ....: "A": ["A0", "A1", "A2", "A3"], ....: "B": ["B0", "B1", "B2", "B3"], ....: } ....: ) ....: In [34]: right = pd.DataFrame( ....: { ....: "key": ["K0", "K1", "K2", "K3"], ....: "C": ["C0", "C1", "C2", "C3"], ....: "D": ["D0", "D1", "D2", "D3"], ....: } ....: ) ....: In [35]: result = pd.merge(left, right, on="key") Here is a more complicated example with multiple join keys. Only the keys appearing in In [36]: left = pd.DataFrame( ....: { ....: "key1": ["K0", "K0", "K1", "K2"], ....: "key2": ["K0", "K1", "K0", "K1"], ....: "A": ["A0", "A1", "A2", "A3"], ....: "B": ["B0", "B1", "B2", "B3"], ....: } ....: ) ....: In [37]: right = pd.DataFrame( ....: { ....: "key1": ["K0", "K1", "K1", "K2"], ....: "key2": ["K0", "K0", "K0", "K0"], ....: "C": ["C0", "C1", "C2", "C3"], ....: "D": ["D0", "D1", "D2", "D3"], ....: } ....: ) ....: In [38]: result = pd.merge(left, right, on=["key1", "key2"]) The
In [39]: result = pd.merge(left, right, how="left", on=["key1", "key2"]) In [40]: result = pd.merge(left, right, how="right", on=["key1", "key2"]) In [41]: result = pd.merge(left, right, how="outer", on=["key1", "key2"]) In [42]: result = pd.merge(left, right, how="inner", on=["key1", "key2"]) In [43]: result = pd.merge(left, right, how="cross") You can merge a mult-indexed Series and a DataFrame, if the names of the MultiIndex correspond to the columns from the DataFrame. Transform the Series to a DataFrame using
In [44]: df = pd.DataFrame({"Let": ["A", "B", "C"], "Num": [1, 2, 3]}) In [45]: df Out[45]: Let Num 0 A 1 1 B 2 2 C 3 In [46]: ser = pd.Series( ....: ["a", "b", "c", "d", "e", "f"], ....: index=pd.MultiIndex.from_arrays( ....: [["A", "B", "C"] * 2, [1, 2, 3, 4, 5, 6]], names=["Let", "Num"] ....: ), ....: ) ....: In [47]: ser Out[47]: Let Num A 1 a B 2 b C 3 c A 4 d B 5 e C 6 f dtype: object In [48]: pd.merge(df, ser.reset_index(), on=["Let", "Num"]) Out[48]: Let Num 0 0 A 1 a 1 B 2 b 2 C 3 c 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¶Users can use the In the following
example, there are duplicate values of In [52]: left = pd.DataFrame({"A": [1, 2], "B": [1, 2]}) In [53]: right = pd.DataFrame({"A": [4, 5, 6], "B": [2, 2, 2]}) 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 In [54]: pd.merge(left, right, on="B", how="outer", validate="one_to_many") Out[54]: A_x B A_y 0 1 1 NaN 1 2 2 4.0 2 2 2 5.0 3 2 2 6.0 The merge indicator¶
In [55]: df1 = pd.DataFrame({"col1": [0, 1], "col_left": ["a", "b"]}) In [56]: df2 = pd.DataFrame({"col1": [1, 2, 2], "col_right": [2, 2, 2]}) In [57]: pd.merge(df1, df2, on="col1", how="outer", indicator=True) Out[57]: col1 col_left col_right _merge 0 0 a NaN left_only 1 1 b 2.0 both 2 2 NaN 2.0 right_only 3 2 NaN 2.0 right_only The In [58]: pd.merge(df1, df2, on="col1", how="outer", indicator="indicator_column") Out[58]: col1 col_left col_right indicator_column 0 0 a NaN left_only 1 1 b 2.0 both 2 2 NaN 2.0 right_only 3 2 NaN 2.0 right_only Merge dtypes¶Merging will preserve the dtype of the join keys. In [59]: left = pd.DataFrame({"key": [1], "v1": [10]}) In [60]: left Out[60]: key v1 0 1 10 In [61]: right = pd.DataFrame({"key": [1, 2], "v1": [20, 30]}) In [62]: right Out[62]: key v1 0 1 20 1 2 30 We are able to preserve the join keys: In [63]: pd.merge(left, right, how="outer") Out[63]: key v1 0 1 10 1 1 20 2 2 30 In [64]: pd.merge(left, right, how="outer").dtypes Out[64]: key int64 v1 int64 dtype: object Of course if you have missing values that are introduced, then the resulting dtype will be upcast. In [65]: pd.merge(left, right, how="outer", on="key") Out[65]: key v1_x v1_y 0 1 10.0 20 1 2 NaN 30 In [66]: pd.merge(left, right, how="outer", on="key").dtypes Out[66]: key int64 v1_x float64 v1_y int64 dtype: object Merging will preserve The left frame. In [67]: from pandas.api.types import CategoricalDtype In [68]: X = pd.Series(np.random.choice(["foo", "bar"], size=(10,))) In [69]: X = X.astype(CategoricalDtype(categories=["foo", "bar"])) In [70]: left = pd.DataFrame( ....: {"X": X, "Y": np.random.choice(["one", "two", "three"], size=(10,))} ....: ) ....: In [71]: left Out[71]: X Y 0 bar one 1 foo one 2 foo three 3 bar three 4 foo one 5 bar one 6 bar three 7 bar three 8 bar three 9 foo three In [72]: left.dtypes Out[72]: X category Y object dtype: object The right frame. In [73]: right = pd.DataFrame( ....: { ....: "X": pd.Series(["foo", "bar"], dtype=CategoricalDtype(["foo", "bar"])), ....: "Z": [1, 2], ....: } ....: ) ....: In [74]: right Out[74]: X Z 0 foo 1 1 bar 2 In [75]: right.dtypes Out[75]: X category Z int64 dtype: object The merged result: In [76]: result = pd.merge(left, right, how="outer") In [77]: result Out[77]: X Y Z 0 bar one 2 1 bar three 2 2 bar one 2 3 bar three 2 4 bar three 2 5 bar three 2 6 foo one 1 7 foo three 1 8 foo one 1 9 foo three 1 In [78]: result.dtypes Out[78]: X category Y object Z int64 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 the categories’ dtype. Note Merging on Joining on index¶
In [79]: left = pd.DataFrame( ....: {"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}, index=["K0", "K1", "K2"] ....: ) ....: In [80]: right = pd.DataFrame( ....: {"C": ["C0", "C2", "C3"], "D": ["D0", "D2", "D3"]}, index=["K0", "K2", "K3"] ....: ) ....: In [81]: result = left.join(right) In [82]: result = left.join(right, how="outer") The same as above, but with In [83]: result = left.join(right, how="inner") The data alignment here is on the indexes (row labels). This same behavior can be
achieved using In [84]: result = pd.merge(left, right, left_index=True, right_index=True, how="outer") In [85]: result = pd.merge(left, right, left_index=True, right_index=True, how="inner") Joining key columns on an index¶
left.join(right, on=key_or_keys) pd.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 In [86]: left = pd.DataFrame( ....: { ....: "A": ["A0", "A1", "A2", "A3"], ....: "B": ["B0", "B1", "B2", "B3"], ....: "key": ["K0", "K1", "K0", "K1"], ....: } ....: ) ....: In [87]: right = pd.DataFrame({"C": ["C0", "C1"], "D": ["D0", "D1"]}, index=["K0", "K1"]) In [88]: result = left.join(right, on="key") In [89]: result = pd.merge( ....: left, right, left_on="key", right_index=True, how="left", sort=False ....: ) ....: To join on multiple keys, the passed DataFrame must have a In [90]: left = pd.DataFrame( ....: { ....: "A": ["A0", "A1", "A2", "A3"], ....: "B": ["B0", "B1", "B2", "B3"], ....: "key1": ["K0", "K0", "K1", "K2"], ....: "key2": ["K0", "K1", "K0", "K1"], ....: } ....: ) ....: In [91]: index = pd.MultiIndex.from_tuples( ....: [("K0", "K0"), ("K1", "K0"), ("K2", "K0"), ("K2", "K1")] ....: ) ....: In [92]: right = pd.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 [93]: result = left.join(right, on=["key1", "key2"]) The default for
In [94]: result = left.join(right, on=["key1", "key2"], how="inner") As 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 In [95]: left = pd.DataFrame( ....: {"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}, ....: index=pd.Index(["K0", "K1", "K2"], name="key"), ....: ) ....: In [96]: index = pd.MultiIndex.from_tuples( ....: [("K0", "Y0"), ("K1", "Y1"), ("K2", "Y2"), ("K2", "Y3")], ....: names=["key", "Y"], ....: ) ....: In [97]: right = pd.DataFrame( ....: {"C": ["C0", "C1", "C2", "C3"], "D": ["D0", "D1", "D2", "D3"]}, ....: index=index, ....: ) ....: In [98]: result = left.join(right, how="inner") This is equivalent but less verbose and more memory efficient / faster than this. In [99]: result = pd.merge( ....: left.reset_index(), right.reset_index(), on=["key"], how="inner" ....: ).set_index(["key","Y"]) ....: Joining with two MultiIndexes¶This is supported in a limited way, provided that the index for the right argument is completely used in the join, and is a subset of the indices in the left argument, as in this example: In [100]: leftindex = pd.MultiIndex.from_product( .....: [list("abc"), list("xy"), [1, 2]], names=["abc", "xy", "num"] .....: ) .....: In [101]: left = pd.DataFrame({"v1": range(12)}, index=leftindex) In [102]: left Out[102]: v1 abc xy num a x 1 0 2 1 y 1 2 2 3 b x 1 4 2 5 y 1 6 2 7 c x 1 8 2 9 y 1 10 2 11 In [103]: rightindex = pd.MultiIndex.from_product( .....: [list("abc"), list("xy")], names=["abc", "xy"] .....: ) .....: In [104]: right = pd.DataFrame({"v2": [100 * i for i in range(1, 7)]}, index=rightindex) In [105]: right Out[105]: v2 abc xy a x 100 y 200 b x 300 y 400 c x 500 y 600 In [106]: left.join(right, on=["abc", "xy"], how="inner") Out[106]: v1 v2 abc xy num a x 1 0 100 2 1 100 y 1 2 200 2 3 200 b x 1 4 300 2 5 300 y 1 6 400 2 7 400 c x 1 8 500 2 9 500 y 1 10 600 2 11 600 If that condition is not satisfied, a join with two multi-indexes can be done using the following code. In [107]: leftindex = pd.MultiIndex.from_tuples( .....: [("K0", "X0"), ("K0", "X1"), ("K1", "X2")], names=["key", "X"] .....: ) .....: In [108]: left = pd.DataFrame( .....: {"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}, index=leftindex .....: ) .....: In [109]: rightindex = pd.MultiIndex.from_tuples( .....: [("K0", "Y0"), ("K1", "Y1"), ("K2", "Y2"), ("K2", "Y3")], names=["key", "Y"] .....: ) .....: In [110]: right = pd.DataFrame( .....: {"C": ["C0", "C1", "C2", "C3"], "D": ["D0", "D1", "D2", "D3"]}, index=rightindex .....: ) .....: In [111]: result = pd.merge( .....: left.reset_index(), right.reset_index(), on=["key"], how="inner" .....: ).set_index(["key", "X", "Y"]) .....: Merging on a combination of columns and index levels¶Strings passed as the In [112]: left_index = pd.Index(["K0", "K0", "K1", "K2"], name="key1") In [113]: left = pd.DataFrame( .....: { .....: "A": ["A0", "A1", "A2", "A3"], .....: "B": ["B0", "B1", "B2", "B3"], .....: "key2": ["K0", "K1", "K0", "K1"], .....: }, .....: index=left_index, .....: ) .....: In [114]: right_index = pd.Index(["K0", "K1", "K2", "K2"], name="key1") In [115]: right = pd.DataFrame( .....: { .....: "C": ["C0", "C1", "C2", "C3"], .....: "D": ["D0", "D1", "D2", "D3"], .....: "key2": ["K0", "K0", "K0", "K1"], .....: }, .....: index=right_index, .....: ) .....: In [116]: result = left.merge(right, on=["key1", "key2"]) Note When DataFrames are merged on a string that matches an index level in both frames, the index level is preserved as an index level in the resulting DataFrame. Note When DataFrames are merged using only some of the levels of a Note If a string matches both a column name and an index level name, then a warning is issued and the column takes precedence. This will result in an ambiguity error in a future version. Overlapping value columns¶The merge In [117]: left = pd.DataFrame({"k": ["K0", "K1", "K2"], "v": [1, 2, 3]}) In [118]: right = pd.DataFrame({"k": ["K0", "K0", "K3"], "v": [4, 5, 6]}) In [119]: result = pd.merge(left, right, on="k") In [120]: result = pd.merge(left, right, on="k", suffixes=("_l", "_r"))
In [121]: left = left.set_index("k") In [122]: right = right.set_index("k") In [123]: result = left.join(right, lsuffix="_l", rsuffix="_r") Joining multiple DataFrames¶A list or tuple of In [124]: right2 = pd.DataFrame({"v": [7, 8, 9]}, index=["K1", "K1", "K2"]) In [125]: result = left.join([right, right2]) Merging together values within Series or DataFrame columns¶Another fairly common situation is to have two like-indexed (or similarly indexed) In [126]: df1 = pd.DataFrame( .....: [[np.nan, 3.0, 5.0], [-4.6, np.nan, np.nan], [np.nan, 7.0, np.nan]] .....: ) .....: In [127]: df2 = pd.DataFrame([[-42.6, np.nan, -8.2], [-5.0, 1.6, 4]], index=[1, 2]) For this, use the
In [128]: result = df1.combine_first(df2) Note that this method only takes values from the right In [129]: df1.update(df2) Timeseries friendly merging¶Merging ordered data¶A
In [130]: left = pd.DataFrame( .....: {"k": ["K0", "K1", "K1", "K2"], "lv": [1, 2, 3, 4], "s": ["a", "b", "c", "d"]} .....: ) .....: In [131]: right = pd.DataFrame({"k": ["K1", "K2", "K4"], "rv": [1, 2, 3]}) In [132]: pd.merge_ordered(left, right, fill_method="ffill", left_by="s") Out[132]: k lv s rv 0 K0 1.0 a NaN 1 K1 1.0 a 1.0 2 K2 1.0 a 2.0 3 K4 1.0 a 3.0 4 K1 2.0 b 1.0 5 K2 2.0 b 2.0 6 K4 2.0 b 3.0 7 K1 3.0 c 1.0 8 K2 3.0 c 2.0 9 K4 3.0 c 3.0 10 K1 NaN d 1.0 11 K2 4.0 d 2.0 12 K4 4.0 d 3.0 Merging asof¶A Optionally an asof merge can perform a group-wise merge. This matches the For example; we might have In [133]: trades = pd.DataFrame( .....: { .....: "time": pd.to_datetime( .....: [ .....: "20160525 13:30:00.023", .....: "20160525 13:30:00.038", .....: "20160525 13:30:00.048", .....: "20160525 13:30:00.048", .....: "20160525 13:30:00.048", .....: ] .....: ), .....: "ticker": ["MSFT", "MSFT", "GOOG", "GOOG", "AAPL"], .....: "price": [51.95, 51.95, 720.77, 720.92, 98.00], .....: "quantity": [75, 155, 100, 100, 100], .....: }, .....: columns=["time", "ticker", "price", "quantity"], .....: ) .....: In [134]: quotes = pd.DataFrame( .....: { .....: "time": pd.to_datetime( .....: [ .....: "20160525 13:30:00.023", .....: "20160525 13:30:00.023", .....: "20160525 13:30:00.030", .....: "20160525 13:30:00.041", .....: "20160525 13:30:00.048", .....: "20160525 13:30:00.049", .....: "20160525 13:30:00.072", .....: "20160525 13:30:00.075", .....: ] .....: ), .....: "ticker": ["GOOG", "MSFT", "MSFT", "MSFT", "GOOG", "AAPL", "GOOG", "MSFT"], .....: "bid": [720.50, 51.95, 51.97, 51.99, 720.50, 97.99, 720.50, 52.01], .....: "ask": [720.93, 51.96, 51.98, 52.00, 720.93, 98.01, 720.88, 52.03], .....: }, .....: columns=["time", "ticker", "bid", "ask"], .....: ) .....: In [135]: trades Out[135]: time ticker price quantity 0 2016-05-25 13:30:00.023 MSFT 51.95 75 1 2016-05-25 13:30:00.038 MSFT 51.95 155 2 2016-05-25 13:30:00.048 GOOG 720.77 100 3 2016-05-25 13:30:00.048 GOOG 720.92 100 4 2016-05-25 13:30:00.048 AAPL 98.00 100 In [136]: quotes Out[136]: time ticker bid ask 0 2016-05-25 13:30:00.023 GOOG 720.50 720.93 1 2016-05-25 13:30:00.023 MSFT 51.95 51.96 2 2016-05-25 13:30:00.030 MSFT 51.97 51.98 3 2016-05-25 13:30:00.041 MSFT 51.99 52.00 4 2016-05-25 13:30:00.048 GOOG 720.50 720.93 5 2016-05-25 13:30:00.049 AAPL 97.99 98.01 6 2016-05-25 13:30:00.072 GOOG 720.50 720.88 7 2016-05-25 13:30:00.075 MSFT 52.01 52.03 By default we are taking the asof of the quotes. In [137]: pd.merge_asof(trades, quotes, on="time", by="ticker") Out[137]: time ticker price quantity bid ask 0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.96 1 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.98 2 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.93 3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93 4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN We only asof within In [138]: pd.merge_asof(trades, quotes, on="time", by="ticker", tolerance=pd.Timedelta("2ms")) Out[138]: time ticker price quantity bid ask 0 2016-05-25 13:30:00.023 MSFT 51.95 75 51.95 51.96 1 2016-05-25 13:30:00.038 MSFT 51.95 155 NaN NaN 2 2016-05-25 13:30:00.048 GOOG 720.77 100 720.50 720.93 3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93 4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN We only asof within In [139]: pd.merge_asof( .....: trades, .....: quotes, .....: on="time", .....: by="ticker", .....: tolerance=pd.Timedelta("10ms"), .....: allow_exact_matches=False, .....: ) .....: Out[139]: time ticker price quantity bid ask 0 2016-05-25 13:30:00.023 MSFT 51.95 75 NaN NaN 1 2016-05-25 13:30:00.038 MSFT 51.95 155 51.97 51.98 2 2016-05-25 13:30:00.048 GOOG 720.77 100 NaN NaN 3 2016-05-25 13:30:00.048 GOOG 720.92 100 NaN NaN 4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN Comparing objects¶The This feature was added in V1.1.0. For example, you might want to compare two In [140]: df = pd.DataFrame( .....: { .....: "col1": ["a", "a", "b", "b", "a"], .....: "col2": [1.0, 2.0, 3.0, np.nan, 5.0], .....: "col3": [1.0, 2.0, 3.0, 4.0, 5.0], .....: }, .....: columns=["col1", "col2", "col3"], .....: ) .....: In [141]: df Out[141]: col1 col2 col3 0 a 1.0 1.0 1 a 2.0 2.0 2 b 3.0 3.0 3 b NaN 4.0 4 a 5.0 5.0 In [142]: df2 = df.copy() In [143]: df2.loc[0, "col1"] = "c" In [144]: df2.loc[2, "col3"] = 4.0 In [145]: df2 Out[145]: col1 col2 col3 0 c 1.0 1.0 1 a 2.0 2.0 2 b 3.0 4.0 3 b NaN 4.0 4 a 5.0 5.0 In [146]: df.compare(df2) Out[146]: col1 col3 self other self other 0 a c NaN NaN 2 NaN NaN 3.0 4.0 By default, if two corresponding values are equal, they will
be shown as If you wish, you may choose to stack the differences on rows. In [147]: df.compare(df2, align_axis=0) Out[147]: col1 col3 0 self a NaN other c NaN 2 self NaN 3.0 other NaN 4.0 If you wish to keep all original rows and columns, set In [148]: df.compare(df2, keep_shape=True) Out[148]: col1 col2 col3 self other self other self other 0 a c NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN NaN 2 NaN NaN NaN NaN 3.0 4.0 3 NaN NaN NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN NaN You may also keep all the original values even if they are equal. In [149]: df.compare(df2, keep_shape=True, keep_equal=True) Out[149]: col1 col2 col3 self other self other self other 0 a c 1.0 1.0 1.0 1.0 1 a a 2.0 2.0 2.0 2.0 2 b b 3.0 3.0 3.0 4.0 3 b b NaN NaN 4.0 4.0 4 a a 5.0 5.0 5.0 5.0 Can we merge 3 DataFrames in Python?You can use the same approach to merge more than three DataFrames. Alternatively, you can also use DataFrame. merge() to join multiple pandas DataFrames.
How do I concatenate a list of DataFrames in pandas?The simplest concatenation with concat() is by passing a list of DataFrames, for example [df1, df2] . And by default, it is concatenating vertically along the axis 0 and preserving all existing indices. If you want the concatenation to ignore existing indices, you can set the argument ignore_index=True .
How do I concatenate two DataFrame columns in Python?By use + operator simply you can concatenate two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.
How do I concatenate rows in pandas?We can use the concat function in pandas to append either columns or rows from one DataFrame to another. Let's grab two subsets of our data to see how this works. When we concatenate DataFrames, we need to specify the axis. axis=0 tells pandas to stack the second DataFrame UNDER the first one.
|