fred.schwartz
fred.schwartz

Reputation: 2155

Overwrite some rows in pandas dataframe with ones from another dataframe based on index

I have a pandas dataframe, df1.

I want to overwrite its values with values in df2, where the index and column name match.

I've found a few answers on this site, but nothing that quite does what I want.

df1

   A   B   C
0  33  44  54
1  11  32   54
2  43  55  12
3  43  23  34

df2
   A
0  5555

output

   A   B   C
0  5555  44  54
1  11  32   54
2  43  55  12
3  43  23  34

Upvotes: 2

Views: 1297

Answers (1)

jezrael
jezrael

Reputation: 862521

You can use combine_first with convert to integer if necessary:

df = df2.combine_first(df1).astype(int)
print (df)
      A   B   C
0  5555  44  54
1    11  32  54
2    43  55  12
3    43  23  34

If need check intersection index and columns between both DataFrames:

df2= pd.DataFrame({'A':[5555, 2222],
                   'D':[3333, 4444]},index=[0, 10])

idx = df2.index.intersection(df1.index)
cols = df2.columns.intersection(df1.columns)

df = df2.loc[idx, cols].combine_first(df1).astype(int)
print (df)
      A   B   C
0  5555  44  54
1    11  32  54
2    43  55  12
3    43  23  34

Upvotes: 3

Related Questions