Issue
I want to merge two dataframes by the index columns. My code is:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'a': ['red', 'red', 'red']})
df2 = pd.DataFrame({'b': [1, 2, 2]})
df = df1.merge(df2, how='left', left_on=df1.index, right_on=df2.index)
print(df.head())
key_0 a b
0 0 red 1
1 1 red 2
2 2 red 2
The result has an unwanted column key_0
. Question: How do I get rid of this column (without any drops after the merge)?
Solution
Instead of treating the index-columns as regular columns, I was able to get rid of the key_0
by using the keywords left_index
and right_index
:
df = df1.merge(df2, how='left', left_index=True, right_index=True)
print(df.head())
a b
0 red 1
1 red 2
2 red 2
Answered By - Carsten
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.