Reputation: 178
I have one bigger dataframe ( A ) and a smaller dataframe ( B ).
A ( larger dataframe )
from val null
Abc_1 45 76
Abc_2 46 77
Abc_3 47 78
Abc_4 48 79
Abc_5 49 80
Abc_6 50 81
Abc_7 51 82
Abc_8 52 83
Abc_9 53 84
Abc_10 54 85
.
.
.
B (smaller dataframe)
from null
Abc_3 3
Abc_8 3
Abc_4 5
Abc_1 2
Abc_6 4
.
.
.
The "from" column is the index of both dataframe. The "from" of B dataframe is subset of "from" of A datframe but it is in jumbled manner ( not in the same order as of A dataframe.)
I want to do some operation which will take the "null" of B datframe of respective rows and replace the "null" of the A dataframe
So the resulting dataframe output should look something like this.
from val null
Abc_1 45 2
Abc_2 46 77
Abc_3 47 3
Abc_4 48 5
Abc_5 49 80
Abc_6 50 4
Abc_7 51 82
Abc_8 52 3
Abc_9 53 84
Abc_10 54 85
.
.
.
Upvotes: 2
Views: 226
Reputation: 863291
Use Series.map
by Series
from B
by select null
column an repalce non matched values by original column by Series.fillna
:
A['null'] = A.index.to_series().map(B['null']).fillna(A['null']).astype(int)
print (A)
val null
from
Abc_1 45 2
Abc_2 46 77
Abc_3 47 3
Abc_4 48 5
Abc_5 49 80
Abc_6 50 4
Abc_7 51 82
Abc_8 52 3
Abc_9 53 84
Abc_10 54 85
Or use left join in DataFrame.merge
with DataFrame.pop
for extract column and Series.fillna
:
Notice: This solution is better if need processing multiple columns.
df = A.merge(B, on='from', how='left', suffixes=('','_'))
df['null'] = df.pop('null_').fillna(df['null']).astype(int)
print (df)
val null
from
Abc_1 45 2
Abc_2 46 77
Abc_3 47 3
Abc_4 48 5
Abc_5 49 80
Abc_6 50 4
Abc_7 51 82
Abc_8 52 3
Abc_9 53 84
Abc_10 54 85
Upvotes: 2