how to merge 2 dafaframes based on index in python

To merge two DataFrames based on their index in Python using pandas, you can use the merge function with the left_index and right_index parameters set to True.

Here is an example of how to do it:

main.py
import pandas as pd

# Creating two DataFrames
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'c']}, index=[0, 1, 2])
df2 = pd.DataFrame({'C': [4, 5, 6], 'D': ['d', 'e', 'f']}, index=[1, 2, 3])

# Merging based on index
merged_df = df1.merge(df2, left_index=True, right_index=True)

print(merged_df)
305 chars
11 lines

Output:

main.py
   A  B  C  D
1  2  b  4  d
2  3  c  5  e
42 chars
4 lines

In the example above, we create two DataFrames, df1 and df2, with different index values. Then we use the merge function and specify left_index=True and right_index=True to perform the merge based on the index. The resulting merged DataFrame is stored in merged_df.

Note that the merge will include only the matching rows from both DataFrames based on their index values.

gistlibby LogSnag