Yared J.
Yared J.

Reputation: 241

How to replace columns with matching name

I know this might be very simple, but I can't figure out how to do it.

I have a df with several columns I want to replace, but lets say I have a df like this:

df1:

   A   B
0  a   22
1  b   44 
2  c   100
3  d   6
4  e   12

And another df

df2:

   B
0  11
1  22 
2  50
3  3
4  6

My desired df is

df1:

   A   B
0  a   11
1  b   22 
2  c   50
3  d   3
4  e   6

Also, I don't want to do it one by one, because I have several columns.

Upvotes: 2

Views: 61

Answers (2)

jezrael
jezrael

Reputation: 863741

If length and indexes are same of both df:

df1['B'] = df2.B

If need only add values:

df1['B'] = df2.B.values

If need replace more columns:

df1 = pd.DataFrame({'A':[1,2,3],
                   'B':[3,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5]})

print (df1)
   A  B  C  D
0  1  3  7  1
1  2  5  8  3
2  3  6  9  5

df2 = pd.DataFrame({'A':[7,8,9],
                   'B':[1,6,5],
                   'C':[5,6,6],
                   'D':[7,3,6]})

print (df2)
   A  B  C  D
0  7  1  5  7
1  8  6  6  3
2  9  5  6  6

df1[['B', 'C', 'D']] = df2[['B', 'C', 'D']]
print (df1)
   A  B  C  D
0  1  1  5  7
1  2  6  6  3
2  3  5  6  6

Upvotes: 4

user4280261
user4280261

Reputation:

The code below is crude, and could be improved, but tell me if does what you want first. Supposing that you have one dataframe's length superior to the other:

def replace(dfa, dfb):
    a_ = [match for match in df1.columns.values if match in df2.columns.values]
    if len(dfa.columns) > len(dfb.columns):
        for value in a_:
            dfa[[value]] = dfb[[value]] 
    else:
        for value in a_:
            dfb[[value]] = dfb[[value]]

You could test with your df1 and df2

Upvotes: 2

Related Questions