amin amin - 1 month ago 18
Python Question

Embedding modified sub-frame into the original one

I have 2 pandas data frames which one of them consists the modified selected rows of the first one (they have similar columns).
For simplicity the below frames illustrate this problem.

df1 = df2 =
A B C A B C
0 1 2 3 1 20 30 40
1 2 3 4 3 40 50 60
2 3 4 5
3 4 5 6


Is there any more efficient and pythonic way than the below code,to embedding the df2 into df1 by overwriting values? (working with high-dimensional frames)

for index, row in df2.iterrows():
df1.ix[index,:] = df2.ix[index, :]


which results in:

df1 =
A B C
0 1 2 3
1 20 30 40
2 3 4 5
3 40 50 60

Answer

You can use update to update a df with another df, where the row and column labels agree the values are updated, you will need to cast to int using astype because the dtype is changed to float due to missing values:

In [21]:
df1.update(df2)
df1 = df1.astype(int)
df1

Out[21]:
    A   B   C
0   1   2   3
1  20  30  40
2   3   4   5
3  40  50  60