- DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=None, indicator=False, validate=None)[source]#
Merge DataFrame or named Series objects with a database-style join.
A named Series object is treated as a DataFrame with a single named column.
The join is done on columns or indexes. If joining columns oncolumns, the DataFrame indexes will be ignored. Otherwise if joining indexeson indexes or indexes on a column or columns, the index will be passed on.When performing a cross merge, no column specifications to merge on areallowed.
Warning
If both key columns contain rows where the key is a null value, thoserows will be matched against each other. This is different from usual SQLjoin behaviour and can lead to unexpected results.
- Parameters:
- rightDataFrame or named Series
Object to merge with.
- how{‘left’, ‘right’, ‘outer’, ‘inner’, ‘cross’}, 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 outerjoin; sort keys lexicographically.
inner: use intersection of keys from both frames, similar to a SQL innerjoin; preserve the order of the left keys.
cross: creates the cartesian product from both frames, preserves the orderof the left keys.
- onlabel or list
Column or index level names to join on. These must be found in bothDataFrames. If on is None and not merging on indexes then this defaultsto the intersection of the columns in both DataFrames.
- left_onlabel or list, or array-like
Column or index level names to join on in the left DataFrame. Can alsobe an array or list of arrays of the length of the left DataFrame.These arrays are treated as if they are columns.
- right_onlabel or list, or array-like
Column or index level names to join on in the right DataFrame. Can alsobe an array or list of arrays of the length of the right DataFrame.These arrays are treated as if they are columns.
- left_indexbool, default False
Use the index from the left DataFrame as the join key(s). If it is aMultiIndex, the number of keys in the other DataFrame (either the indexor a number of columns) must match the number of levels.
- right_indexbool, default False
Use the index from the right DataFrame as the join key. Same caveats asleft_index.
- sortbool, default False
Sort the join keys lexicographically in the result DataFrame. If False,the order of the join keys depends on the join type (how keyword).
- suffixeslist-like, default is (“_x”, “_y”)
A length-2 sequence where each element is optionally a stringindicating the suffix to add to overlapping column names inleft and right respectively. Pass a value of None insteadof a string to indicate that the column name from left orright should be left as-is, with no suffix. At least one of thevalues must not be None.
- copybool, default True
If False, avoid copy if possible.
Note
The copy keyword will change behavior in pandas 3.0.Copy-on-Writewill be enabled by default, which means that all methods with acopy keyword will use a lazy copy mechanism to defer the copy andignore the copy keyword. The copy keyword will be removed in afuture version of pandas.
You can already get the future behavior and improvements throughenabling copy on write
pd.options.mode.copy_on_write = True
- indicatorbool or str, default False
If True, adds a column to the output DataFrame called “_merge” withinformation on the source of each row. The column can be given a differentname by providing a string argument. The column will have a Categoricaltype with the value of “left_only” for observations whose merge key onlyappears in the left DataFrame, “right_only” for observationswhose merge key only appears in the right DataFrame, and “both”if the observation’s merge key is found in both DataFrames.
- validatestr, optional
If specified, checks if merge is of specified type.
“one_to_one” or “1:1”: check if merge keys are unique in bothleft and right datasets.
“one_to_many” or “1:m”: check if merge keys are unique in leftdataset.
“many_to_one” or “m:1”: check if merge keys are unique in rightdataset.
“many_to_many” or “m:m”: allowed, but does not result in checks.
- Returns:
- DataFrame
A DataFrame of the two merged objects.
See also
- merge_ordered
Merge with optional filling/interpolation.
- merge_asof
Merge on nearest keys.
- DataFrame.join
Similar method using indices.
Examples
>>> df1 = pd.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'],... 'value': [1, 2, 3, 5]})>>> df2 = pd.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'],... 'value': [5, 6, 7, 8]})>>> df1 lkey value0 foo 11 bar 22 baz 33 foo 5>>> df2 rkey value0 foo 51 bar 62 baz 73 foo 8
Merge df1 and df2 on the lkey and rkey columns. The value columns havethe default suffixes, _x and _y, appended.
>>> df1.merge(df2, left_on='lkey', right_on='rkey') lkey value_x rkey value_y0 foo 1 foo 51 foo 1 foo 82 bar 2 bar 63 baz 3 baz 74 foo 5 foo 55 foo 5 foo 8
Merge DataFrames df1 and df2 with specified left and right suffixesappended to any overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey',... suffixes=('_left', '_right')) lkey value_left rkey value_right0 foo 1 foo 51 foo 1 foo 82 bar 2 bar 63 baz 3 baz 74 foo 5 foo 55 foo 5 foo 8
Merge DataFrames df1 and df2, but raise an exception if the DataFrames haveany overlapping columns.
>>> df1.merge(df2, left_on='lkey', right_on='rkey', suffixes=(False, False))Traceback (most recent call last):...ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
>>> df1 = pd.DataFrame({'a': ['foo', 'bar'], 'b': [1, 2]})>>> df2 = pd.DataFrame({'a': ['foo', 'baz'], 'c': [3, 4]})>>> df1 a b0 foo 11 bar 2>>> df2 a c0 foo 31 baz 4
>>> df1.merge(df2, how='inner', on='a') a b c0 foo 1 3
>>> df1.merge(df2, how='left', on='a') a b c0 foo 1 3.01 bar 2 NaN
>>> df1 = pd.DataFrame({'left': ['foo', 'bar']})>>> df2 = pd.DataFrame({'right': [7, 8]})>>> df1 left0 foo1 bar>>> df2 right0 71 8
>>> df1.merge(df2, how='cross') left right0 foo 71 foo 82 bar 73 bar 8
pandas.DataFrame.merge — pandas 2.2.2 documentation (2024)
Top Articles
Latest Posts
Recommended Articles
- Who Is Ge Zhang Dating 2021
- Who is Kyojuro Rengoku, the Flame Hashira, in Demon Slayer?
- Descargar Northbury Grove: Entity Gratis
- Meteor Methuselah Webtoon
- Stuart Mcdonald Hub
- The Best Water Flossers for Your Money
- The Five Killers Based On True Story
- Performance status score: do patients and their oncologists agree?
- How To Update Worm War: Greengrocer Pc
- Kraken Hidden Expedition: New Adventures Steve And Victoria
- Larry Wheels: From Hardship to Record-Breaking Fitness Icon Across Multiple Sports
- D Gukesh vs Ding Liren Highlights: Gukesh beats Liren in Round 3, wins his first match in World Chess Championship 2024
- Kansas City's other Chiefs want to build a 'high impact' dynasty in wheelchair football
- Black Knight Title Cards
- This No7 gift set saves you £100 on skincare and make-up bestsellers
- Aruka Aida Meet And Greet
- Steve Genewick Pink Hair
- Watch Dil Hi Dil Mein (2000)
- Golden Days 29
- Sleep Duration Is Associated With Testis Size in Healthy Young Men
- How Many Movies Are There Of Funeral For A Dog
- Free Screen Recorder | Loom
- Pink Chime After 5 Renders
- Is Room Escape: Strange Case 2 Available On Xbox
- The 10 Best Electric Nail Files of 2024 (Reviews) - FindThisBest
- Goodbye Dragon Life Season 2 Release Date On Netflix
- Jellybean Benítez Snubbed
- Final Fantasy Lost Stranger Cafe Japan
- What Is The Meaning Behind Timbuktu (2014)
- Every Junji Ito Book - Your Reading Guide - Amanja Reads Too Much
- Season 2 Of Is It Wrong To Try To Pick Up Girls In A Dungeon? Iv Release Date
- Nhk Ni Youkoso! Chapter 250
- Your Signature Scent Is a Click Away With the 18 Best Online Retailers to Buy Perfume
- Stubborn Calluses? These Foot Peels Will Eliminate Them Within Days
- How old was Tabitha St. Germain in…
- Who Directed 青春並不溫柔 (2023)
- 5 Best Makeup Sets - Dec. 2024 - BestReviews
- Tipirneni wins race to take on Schweikert; House incumbents on track to win primaries
- How to Remove Your Makeup Like a Dermatologist (And a Veteran Makeup Artist)
- Best Lake Falcon Fishing Guide
- Deimos No Hanayome Episode 33
- A Fairy Tale Game Of Tag Season 2 Episode 5 Gogoanime
- Why is Fortnite so Laggy? 8 Quick Fixes
- Die andere Zoey: Die Handlung & das Ende erklärt | Popkultur.de
- Spirit Hunter: Death Mark Ii Is
- Marriage Exchange: The Night Of No Return Movie Theatres
- Skinner’s Box Experiment (Behaviorism Study)
- Bakeneko - Mythical Encyclopedia
- German Missions in India
- La Guerre est pour demain [celle de 39-45] Ludwig Bauer • EUR 4,90
- Shirogane X Spirits App Id
- The Worn And Torn Newbie Reaction Gif
- Actor That Looks Like Trinidad González
- Doraemon The Movie: Nobita's Diary Of The Creation Of The World Reaction Faces
- Handytarife und Flat für 5 Euro - diese Angebote sind zu empfehlen
- Kido: Ride On Time Steam Mac
- Tails And The Music Maker Pre Order Collector's Edition
- The Best Lighted Makeup Mirrors
- vabali spa Düsseldorf
- Minecraft 1.21.3 Resource Packs | Texture Packs
- A Certain Magical "Index"? New Animation
- How to Turn Off AI in the iPhone Mail App
- Harry Carey Speaks Out
- Oomuro-Ke: Dear Sisters Ep 1 Season 2
- Stuart Hogg 4Th Of July
- Mahjong Titan Not On Steam
- Has the email hacking scandal spread from Britain to Australia? Meet Heather Kennett and Matt Deighton
- How Many Words Are In Sabata (1969)
- Appointment With Death Gaming Pc
- Honoka Level Up! Episode 3 Season 2
- The 10 Best Shower Mirrors of 2024 (Reviews) - FindThisBest
- Stephen Davis 50
- Best Starvation Settings Xbox
- TOTALTOOLS 20L Tradie Plastic Bucket with Handle and Lid Red TTKIT1007
- Antony Byrne | Pathways to Shakespeare Blog | Royal Shakespeare Company
- Supercharged Baba Ganoush (Eggplant Dip with Chickpeas)
- 【DC】1422个DC官方游戏redump全集下载-游戏星辰
- The Last Night Bed Sheets
- Sora Ni Hibiku Coloring
- The King Of Pigs Merch
- CBLE RESULT: November 2024 Customs Broker board exam list of passers
- Beautiful Batsukh Batsuuri
- You-Jitsu Intro 1
- Análisis de la mezcla de marketing de productos de papel sanitario de un solo uso 2025
- Don't Want People to Know Your Tan Is Fake? Let Me Introduce You to These 10 Gradual Self-Tanners
- Stainless Steel Pipe, 3-1/2" DIA x Various Lengths - materials - by dealer - sale - craigslist
- Ni No Kuni Season 2 Episode 14
- 12 Best Press-On Nails That Are Better Than a Gel or Acrylic Manicure
- 12 Best Press-On Nails That Are Better Than a Gel or Acrylic Manicure
- 12 Best Press-On Nails That Are Better Than a Gel or Acrylic Manicure
- 12 Best Press-On Nails That Are Better Than a Gel or Acrylic Manicure
- 12 Best Press-On Nails That Are Better Than a Gel or Acrylic Manicure
- Lundi Matin (2002) Free
- How To Add Friends On General Mayhem
- What Is Seo Bo-Ra& 39
- Antoine D'agata Speech Impediment
- New Season Mazinkaizer Skl
- Are There Lyrics To Tomka Dhe Shokët E Tij (1977) Song
- Hikaru Ga Shinda Natsu Opening Letra
- 武林世家 Movie Poster
Article information
Author: Eusebia Nader
Last Updated:
Views: 6119
Rating: 5 / 5 (80 voted)
Reviews: 95% of readers found this page helpful
Author information
Name: Eusebia Nader
Birthday: 1994-11-11
Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603
Phone: +2316203969400
Job: International Farming Consultant
Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting
Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.