D
D
Danil Samodurov2021-08-08 10:06:12
Python
Danil Samodurov, 2021-08-08 10:06:12

How to replace part of a DataFrame array with another DataFrame array in pandas?

Hello. Something turned me on. Can't remember the command to replace part of a DataFrame with another DataFrame. Both arrays are the same length, and have common columns. It is necessary that these common columns in one of them be replaced by the same columns from the other. How to do it?

I know it can be done like this:

df3 = df1.replace(df1.to_dict(orient='list'), df2.to_dict(orient='list'))

But this takes a very long time, it is easier to do it by brute force.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-08-08
@LazyTalent

>>> import pandas as pd

>>> 
>>> df1 = pd.DataFrame({'item': [1, 2, 3, 4], 'val1': [213, 31, 12, 2132], 'val2': [54, 322, 23, 23]})
>>> df2 = pd.DataFrame({'item': [1, 2, 3, 4], 'val1': [213, 31, 12, 2132], 'val2': [32112, 132412, 1354112, 123412]})
>>> 
>>> df1 = df1
>>> df2 = df2
>>> 
>>> df = df1.merge(df2, on='item', how='inner')
>>> df
   item  val1     val2
0     1   213    32112
1     2    31   132412
2     3    12  1354112
3     4  2132   123412
>>>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question