Suppose I have two data frame 'df_a' & 'df_b' , both have the same index structure and columns, but some of the inside data elements are different:
>>> df_a
sales cogs
STK_ID QT
000876 1 100 100
2 100 100
3 100 100
4 100 100
5 100 100
6 100 100
7 100 100
>>> df_b
sales cogs
STK_ID QT
000876 5 50 50
6 50 50
7 50 50
8 50 50
9 50 50
10 50 50
And now I want to replace the element of df_a by element of df_b which have the same (index, column) coordinate, and attach df_b's elements whose (index, column) coordinate beyond the scope of df_a . Just like add a patch 'df_b' to 'df_a' :
>>> df_c = patch(df_a,df_b)
sales cogs
STK_ID QT
000876 1 100 100
2 100 100
3 100 100
4 100 100
5 50 50
6 50 50
7 50 50
8 50 50
9 50 50
10 50 50
How to write the 'patch(df_a,df_b)' function ?
Try this:
df_c = df_a.reindex(df_a.index | df_b.index)
df_c.ix[df_b.index] = df_b
To fill gaps in one dataframe with values (or even full rows) from another, take a look at the df.combine_first() built-in method.
In [34]: df_b.combine_first(df_a)
Out[34]:
sales cogs
STK_ID QT
000876 1 100 100
2 100 100
3 100 100
4 100 100
5 50 50
6 50 50
7 50 50
8 50 50
9 50 50
10 50 50
Similar to BrenBarn's answer, but with more flexibility:
# reindex both to union of indices
df_ar = df_a.reindex(df_a.index | df_b.index)
df_br = df_b.reindex(df_a.index | df_b.index)
# replacement criteria can be put in this lambda function
combiner = lambda: x, y: np.where(y < x, y, x)
df_c = df_ar.combine(df.br, combiner)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With