Yashash GC
Yashash GC

Reputation: 11

How to merge two dataframes with different column names but same number of rows?

I have two different data frames in pandas. Example:

df1=a b  df2= c
    0 1       1 
    1 2       2 
    2 3       3 

I want to merge them so

df1= a b c  
     0 1 1
     1 2 2
     2 3 3

I tried using df1['c'] = df2['c'] but i got a settingwithCopywarnings

Upvotes: 1

Views: 1590

Answers (1)

estebanpdl
estebanpdl

Reputation: 1233

In order to merge two dataframes you can use this two examples. Both returns the same goal.

Using merge plus additional arguments instructing it to use the indexes

Try this:

response = pandas.merge(df1, df2, left_index=True, right_index=True)
In [2]: response
Out[2]:
    b   c
0   1   1
1   2   2
2   3   3

Or you can use join. In case your daraframes are differently-indexed.

DataFrame.join is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame.

Here is a basic example:

result = df1.join(df2)
In [3]: result
Out[3]:
    b   c
0   1   1
1   2   2
2   3   3

Upvotes: 2

Related Questions