I have a df called df1 like this:
NAME CODE TYPE ........... many other columns
object1 20052020 A
object2 20082021 B
object3 20012031 B
object4 20010123 C
. . .
. . .
. . .
etc etc etc
and i have another df called df2:
NAME CODE ........... many other columns
object1 20052020
object2 20082021
. .
I want to change the TYPE values in df1. I want to make this change only in the common elements between df2 and df1 BY CODE, like this (i changed A type for F type in the common elements):
NAME CODE TYPE ........... many other columns
object1 20052020 F
object2 20082021 F
object3 20012031 B
object4 20010123 C
. . .
. . .
. . .
etc etc etc
Use DataFrame.merge
with boolean indexing
:
df1 = df1.merge(df2['CODE'], on='CODE', how='left', indicator=True)
df1.loc[df1.pop('_merge').eq('both'), 'TYPE'] = 'F'
OR use Series.map
with Series.fillna
,
df1['TYPE']=(
df1['CODE'].map(
df2.set_index('CODE').assign(TYPE='F').pop('TYPE'))
.fillna(df1['TYPE'])
)
Result:
# print(df1)
NAME CODE TYPE
0 object1 20052020 F
1 object2 20082021 F
2 object3 20012031 B
3 object4 20010123 C
Try:
df.set_index('CODE', inplace=True)
df1.set_index('CODE', inplace=True)
df.loc[df.index & df1.index, 'TYPE'] = 'F'
df.reset_index()
CODE NAME TYPE
20052020 object1 F
20082021 object2 F
20012031 object3 B
20010123 object4 C
Don't forget to reset the index
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.