ADVERTISEMENT
ADVERTISEMENT

How to keep index when using pandas merge?

Learn to keep index when using pandas merge.
Submitted by Pranit Sharma, on June 11, 2022

Sometimes, when we merge two DataFrames, the resulting DataFrame has some index pattern which is not our requirement. We want to set the index after merging according to our wish. For this purpose, we will reset the index at the time of merging the DataFrames.

DataFrames are 2-dimensional data structure in pandas. DataFrames consists of rows, columns and the data. The Data inside the DataFrame can be of any type.

To achieve this task, we will first create two separate DataFrames. We will then reset the index using DataFrame.reset_index() method. As we reset the index, we will merge the DataFrame with another DataFrame also we will pass 'how = left' as a parameter if we want the indices of 1st DataFrame or 'how = right' if we want the indices of 2nd DataFrame.

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

# Importing pandas package
import pandas as pd

# Creating a dictionary
d1= {
    'One': [ 1, 2, 3],
    'Value': [ 1, 3, 4]
}

d2 = {
    'Two': [1, 2, 3],
    'Value': [1, 3, 5]
}

# Creating dataframes
df1 = pd.DataFrame(d1, index=['a','b','c'])
df2 = pd.DataFrame(d2, index=[0,1,2])

# Display both DataFrames
print("DataFrame 1:\n",d1,"\n")
print("DataFrame 2:\n",d2,"\n")

# Setting index
result = df1.reset_index().merge(df2,how='left')

# Display result
print("Merged DataFrame with index:\n",result)

Output:

Example: Keep index when using pandas merge

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.