Skip to content

BUG: merge drops index components sometimes, when join is empty #34357

Open
@phofl

Description

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

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

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd

left = pd.DataFrame({'a': [1], 'i': [1]}).set_index(['a', 'i'])
right = pd.DataFrame({'i': [1]}).set_index(['i'])

df = pd.merge(
    left,
    right, 
    left_on="i",
    right_on="i",
    how="left")
print(df)
print(df.reset_index())

df = pd.merge(
    left,
    right,    
    right_index=True,
    left_on="i",
    how="left")
print(df)
print(df.reset_index())

Problem description

The first merge changes the index of the left DataFrame in a way, that the index component a is dropped.

Empty DataFrame
Columns: []
Index: [1]


   i
0  1

The second merge returns the original index respectively DataFrame after resetting the index. I think this is the expected output.

Expected Output

Empty DataFrame
Columns: []
Index: [(1, 1)]


   a  i
0  1  1

Output of pd.show_versions()

Was tested on master.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions