1

I have 2 pandas dataframes. The second one is contained in the first one. How can I replace the values in the first one with the ones in the second?

consider this example:

df1 = pd.DataFrame(0, index=[1,2,3], columns=['a','b','c'])
df2 = pd.DataFrame(1, index=[1, 2], columns=['a', 'c'])

ris= [[1, 0, 1],
      [1, 0, 1],
      [0, 0, 0]]

and ris has the same index and columns of d1

A possible solution is:

for i in df2.index:
  for j in df2.columns:
     df1.loc[i, j] = df2.loc[i, j]

But this is ugly

2 Answers 2

1

I think you can use copy with combine_first:

df3 = df1.copy()
df1[df2.columns] = df2[df2.columns]
print df1.combine_first(df3) 
     a  b    c
1  1.0  0  1.0
2  1.0  0  1.0
3  0.0  0  0.0

Next solution is creating empty new DataFrame df4 with index and columns from df1 and fill it by double combine_first:

df4 = pd.DataFrame(index=df1.index, columns=df1.columns)
df4 = df4.combine_first(df2).combine_first(df1)
print df4
     a    b    c
1  1.0  0.0  1.0
2  1.0  0.0  1.0
3  0.0  0.0  0.0
Sign up to request clarification or add additional context in comments.

Comments

0

Try

In [7]: df1['a'] = df2['a']

In [8]: df1['c'] = df2['c']

In [14]: df1[['a','c']] = df2[['a','c']]

If the column names are not known:

In [25]: for col in df2.columns:
   ....:     df1[col] = df2[col]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.