Skip to content

BUG: pd.merge has unexpected behaviour when joining on index / column #57291

Open
@sledtester

Description

@sledtester

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
df1 = pd.DataFrame([ {'seq':i, 'val_1':10+i} for i in range(10) ])
df2 = pd.DataFrame([ {'seq':i+5, 'val_2':10+i+5} for i in range(10) ])

# This produces NaN's in the index (main result in question)
pd.merge(df1, df2, left_index=True, right_on='seq', how='left')

Issue Description

When joining two data frames, in this case with a left join, using the left_index, I would expect the left index to be taken for this new data frame, not the values from the right column. As well as being unexpected behaviour, this also results in this case in NaNs in the index, which also has the side effect of changing the index type to float - all in all probably not what was intended.

Generate some data
image

df1:
image

df2:
image

join them:
image

Expected Behavior

The resultant dataframe of a left-join with left-index should have the index of the left data frame.

Installed Versions

INSTALLED VERSIONS

commit : fd3f571
python : 3.11.4.final.0
python-bits : 64
OS : Darwin
OS-release : 23.2.0
Version : Darwin Kernel Version 23.2.0: Wed Nov 15 21:54:10 PST 2023; root:xnu-10002.61.3~2/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8

pandas : 2.2.0
numpy : 1.26.3
pytz : 2024.1
dateutil : 2.8.2
setuptools : 69.0.3
pip : 23.3.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.9.9
jinja2 : None
IPython : 8.21.0
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : 2024.2.0
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 15.0.0
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.12.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.4
qtpy : None
pyqt5 : None

Metadata

Metadata

Labels

BugReshapingConcat, Merge/Join, Stack/Unstack, Explode

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions