- 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 (2025)
Top Articles
Hepex Rumors
Flatmates With Benefits Webtoon Nsfw
Micky Lynn: Biography, Age, Height, Figure and Net Worth Revealed - Bio-Famous.com
Latest Posts
Recommended Articles
- Jayne Torvill says farewell tour with Christopher Dean will be ‘quite emotional’
- Where, when Mississippi plans Hands Off protests against Trump admin, Musk cuts on April 5
- What is the most commonly used debt instrument?
- Tesla, chip stocks Intel, Qualcomm tumble as China's retaliation stokes fears of widening trade war
- Photos show how angst against Elon Musk went global during Tesla protests
- Sonia Fowler departs EastEnders – playing trumpet – after more than 30 years
- Black Mirror Almost Borrowed A Key Feature From The Twilight Zone - SlashFilm
- Starmer told to accept Trump ‘free speech’ agenda to win trade deal
- Howie Roseman Unveils New Details on Eagles’ 2025 Draft Strategy
- Survivors urge all political parties to support residential school burial investigations | CBC News
- More Dems work to join Sen. Van Hollen in El Salvador to push for alleged gang member's return to US
- Congress MLA Partap Singh Bajwa Appears Before Cops Over '50 Bombs' remark
- Hershey Company unveils new, advanced chocolate processing facility in Dauphin County
- James Carville blasted for sharing 'hot take' on Kilmar Abrego Garcia
- 'Shortsighted move could be set to blow Britain's future defences'
- Ridley Scott's Kingdom of Heaven director's cut gets a new epic 4K UHD Blu-ray release for the 20th anniversary
- Notre Dame Football Midweek Mailbag
- The Decline of NB-IoT: Why Operators are Shifting to LTE, 5G, and Satellite Connectivity
- 5 Places To Admire Beautiful Cherry Blossoms Around The World
- Teen accused of hiring hitmen revealed as Swede living in Sydney’s west
- O’Neil says Coalition housing policy a ‘melange of weird things’ as data shows Labor behind on building target
- Rancher's dog rescues toddler who wandered 7 miles and spent night alone in Arizona desert
- Three Stars of the Night | NHL.com
- Kyler Gordon’s immediate reaction to $60 million Chicago Bears extension
- Italy's Meloni will test her mettle as EU-U.S. bridge when she meets with Trump
- Ange Postecoglou's 'tough' decision to quit club and take up new challenge
- Singapore can no longer rely on 'working' global trading system to fit into, unlike in past crises: SM Lee
- NCIS Just Threw Some Major Curveballs Into Its LaRoche Storyline, And One Of Them Hit Parker In A Surprising Way
- The FDA warns patients about counterfeit Ozempic that may be in circulation
- U.S. ambassador honours Nigeria’s thriving music industry - The Nation Newspaper
- Taylor Swift and Travis Kelce’s unseen Coachella 2024 moment has shocked fans amidst the Kanye West controversy | NFL News - The Times of India
- Arkansas and Indiana ask Trump administration to let them ban soda and candy from SNAP
- Now get men out of women's jails, says ex governor
- Bitcoin (BTC) Will Definitely Hit $1,000,000: Binance's CZ
- US shooting: 2 dead as police officer’s son opens fire at university
- We Now Know the Price for Nintendo's Controversial Switch 2 Welcome Tour
- How Supreme Court Sacked Abure – THISDAYLIVE
- वर्ष २०८१: स्वास्थ्य क्षेत्रमा उपलब्धि, विवाद र क्षति
- Google TV Streamer 4K review | CHOICE
- Justin Vernon Says Taylor Swift Turned Big Red Machine Demos Into 'Her Strongest Set of Lyrics'
- Get into 4K gaming with this 27-inch IPS monitor, now $330 or 0.004 cents per pixel if you prefer
- The newest Minecraft snapshot makes A Minecraft Movie's giant Ghast airships into an in-game reality
- Rory McIlroy's simple sleep tricks all Brits can follow for better night's rest
- New Genes Linked to Parkinson’s Risk Revealed - Neuroscience News
- Asian markets are mostly higher as Wall Street is stuck in trade war doldrums
- Is Viatris Inc. (VTRS) The Top Healthcare Stock to Buy According to Billionaire David Einhorn?
- What the Supreme Court Got Wrong About Habeas Petitions
- Vietnamese mission to UN extends New Year greetings to Laos, Cambodia
- Should You Be Adding Oracle Corporation Japan (TSE:4716) To Your Watchlist Today?
- ANALYSIS | Alberta separatists getting organized — a unity challenge for Canada and Danielle Smith's party | CBC News
- Long-life expert says 100-year-olds 'love' this purple superfood
- Best gaming PC builds: budget, mid-range and high-end recommendations
- Charli XCX's 'embarrassing' Coachella outfit leaves fans divided
- Leeds angry at offside errors but back on top as James strike sinks Middlesbrough
- DOJ plans to appeal Abrego Garcia ruling, releases documents it says tie him to gang
- An SA man faces life in prison for sacrilege. What does the controversial charge mean?
- Qualcomm debuts new Snapdragon G handheld gaming PC chips to compete with Intel and AMD
- The Future of Smart Homes with IoT in Real Estate
- NYT Connections hints today: Clues, answers for April 9, 2025
- NYT ‘Strands’ Today: Hints, Spangram, Answers For Wednesday, April 16
- Gorgeous California border city is hit by stomach-churning new problem
- Mrs Hinch's baby's diagnosis explained as she warns parents to 'trust their gut'
- Parliament Security Breach Accused Tried To Bring Back 2001 Memories: Cops
- Get 62% Off Tarte’s Viral Cream Eyeshadow That Makes Eyes Look Brighter and Lifted — Plus Free Shipping
- Brits gutted as Lanzarote holidays ruined by flash floods as emergency declared
- $1.2m Luai question exposed as ‘obvious destination’ emerges for Galvin — Crawls
- Perspective: The U.K. strikes a praiseworthy compromise
- Singapore can no longer rely on 'working' global trading system to fit into, unlike in past crises: SM Lee
- Human Cell Maps Uncover Insights in Pediatric Bone Cancer
- My boss treats me like a lazy teenager. How can I set some boundaries? | Ask Annalisa Barbieri
- Democratic prosecutor in crime-torn Albuquerque launches bid for New Mexico governor
- Last Tour responds to the complaint from default to SGAE for concerts of Taylor Swift, Leiva ...
- British Steel: Government aims to take control with emergency law
- IoT accelerating efficiency, cost savings, and sustainable solutions
- Easter travellers warned of fire danger, algal bloom
- State pensioners in line for £230 benefit from Sunday
- Syria hopes tourists will return to Palmyra, a World Heritage Site ravaged by war
- This Photographer Changed Digital Black and White Forever
- Kelvin Odih Begins Official Visit With Utah Basketball
- Did Bobby die on '9-1-1'? Is Peter Krause leaving the show?
- Sixth Harvard nurse diagnosed with brain tumor in possible cluster
- Moment thug pulls up next to London film crew and snatches camera
- Why measles is resurging in vulnerable countries despite global progress
- NASA's SpaceX 32nd Commercial Resupply Mission Overview
- Venezuela will have its first female saint after approval from Pope Francis
- RHOSLC’s Monica Garcia Gives Birth to Baby No. 5
- Uncommon Risks Explain Strokes in Under-50 Adults
- WiFi and Bluetooth LE add-on board targets IoT applications
- Why Arteta called Guardiola before Real Madrid win as Arsenal get £68m boost
- How to file for an extension, and other Tax Day advice
- Pip Edwards shares sweet birthday tribute to her 'main man'
- Where, when Mississippi plans Hands Off protests against Trump admin, Musk cuts on April 5
- Fuse partners with Check Point for real-time blockchain firewall
- First meeting of CDC vaccine advisers under RFK Jr. is mostly 'business as usual'
- Cloudy Bay: the roundabout story of New Zealand's most famous wine
- Days Gone’s upcoming survival arcade mode will introduce endless hordes and ‘exploding freakers’, and I’m beginning to think it might be the best way to play the game
- Ukrainian tennis player Lesia Tsurenko sues WTA and its chairman for causing 'emotional distress'
- Liberal Party data collection site hidden beneath unsubscribe link
- Trump hopes to jail U.S. citizens abroad. And, retail sales jump ahead of tariffs
- The death of Megan Khung: Could intervention have saved her?
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.