Solomon Vimal
Solomon Vimal

Reputation: 1070

Python Pandas: how to overwrite subset of a dataframe with a subset of another dataframe?

Given df1 and df2, how do I get df3 using pandas, where df3 has df1 elements:

[11, 12, 21, 22]

in the place of df2 elements

[22, 23, 32, 33]

Condition: indexes of row 1 & 2 in df1 are the same as indexes of row 2 & 3 in df2

Upvotes: 1

Views: 1828

Answers (1)

firelynx
firelynx

Reputation: 32214

You are looking for the DataFrame.loc method

Small example:

import pandas as pd
df1 = pd.DataFrame({"data":[1,2,3,4,5]})
df2 = pd.DataFrame({"data":[11,12,13,14,15]})
df3 = df1.copy()
df3.loc[3:4] = df2.loc[3:4]

df3
   data
0     1
1     2
2     3
3    14
4    15

Upvotes: 2

Related Questions