Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas - intersect dataframes by index.name

I have two dataframes that share (some) ids (specified in index.name) and I want to intersect them.

So given:

dfA.index.name = 'id'
dfB.index.name = 'id'

and dfA being like:

        count
id       
1         15
3         16
8          1

and dfB being like:

        owns
id 
1       True
3       False
12      False

I want to obtain dfC being like:

        count    owns
id 
1         15      True
3         16      False

I tried

s1 = pd.merge(dfA, dfB, how='inner', on=['id'])

without success

like image 909
andandandand Avatar asked Dec 06 '25 14:12

andandandand


2 Answers

I'd use join in this case:

dfC = dfA.join(dfB, how='inner')
like image 175
MaxU - stop WAR against UA Avatar answered Dec 08 '25 04:12

MaxU - stop WAR against UA


You should merge on indexes, not on columns:

s1 = pd.merge(dfA, dfB, left_index=True, right_index=True)

Assigning a name to an index does not make it a column.

like image 39
DYZ Avatar answered Dec 08 '25 04:12

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!