Line two tables up on a shared column with pd.merge, and choose which rows survive with inner, left, right and outer.
pd.merge lines two tables up on a column they share. Where the key matches, the columns of the second table are attached to the row of the first. Where it does not match, you choose what happens.
In this lesson I attach sector labels to a price table, watch a missing ticker turn into NaN, and then run all four join types on one small pair of frames so you can see which rows each one keeps.
Step 1. Prices and sector labels
Two tables, each with a Ticker column. The prices know nothing about sectors and the sector table knows nothing about prices. The numbers are simulated.
NVDA kept its price and got NaN for Sector, because the sector table has no NVDA row to supply. XOM is still gone: a left join never adds rows that the left table did not already have.
Ticker Close Sector
0 AAPL 185.40 Technology
1 AMZN 178.30 Consumer
2 MSFT 410.20 Technology
3 NVDA 130.75 NaN
4 XOM NaN Energy
(5, 3)
Inner gave 3 rows, left 4, right 4, outer 5. The default is how="inner". Leaving how out drops the unmatched tickers.
prices lists AMZN last and the outer result puts it second: an outer join sorts the key. The left join above kept the left table’s row order.
Step 3. A column that needs both tables
Market capitalisation is price times shares outstanding, and neither table holds both numbers. Merge first, multiply second. Shares outstanding are in billions, and simulated like the rest.
Inner keeps 2 rows, outer keeps 4. META has no price, so its Close is NaN. AAPL has no beta.
NoteWhich side did each row come from?
indicator=True adds a _merge column naming the source of every row.
print(pd.merge(prices, shares, on="Ticker", how="outer", indicator=True))# -> Ticker Close SharesOut _merge# -> 0 AAPL 185.40 15.2 both# -> 1 AMZN 178.30 10.4 both# -> 2 MSFT 410.20 7.4 both# -> 3 NVDA 130.75 NaN left_only# -> 4 XOM NaN 4.0 right_only
Ticker Close SharesOut _merge
0 AAPL 185.40 15.2 both
1 AMZN 178.30 10.4 both
2 MSFT 410.20 7.4 both
3 NVDA 130.75 NaN left_only
4 XOM NaN 4.0 right_only
Count the left_only rows and you know how many tickers your reference table is missing.
NoteWhen the key columns have different names
left_on and right_on take one name each. Both columns survive in the result.
Ticker Close Listing
0 AAPL 185.40 NASDAQ
1 AAPL 185.40 XETRA
2 MSFT 410.20 NaN
3 NVDA 130.75 NaN
4 AMZN 178.30 NaN
Four rows went in and five came out. Check len() before and after a merge, or pass validate="one_to_one" and let pandas raise when the key is not unique on both sides.