I think it is very easy and simple question. but it is very difficult for me. please help! I can write R code
JavaScript
x
2
1
b$v2 <- ifelse(a$key==b$key, a$v2, b$v2)
2
input df a is a df, it have key and answer value. b is a df, it have to change according to a.
JavaScript
1
10
10
1
a1=[11,22,44]
2
a2=['a','b','d']
3
a3={'key':a1, 'v2':a2}
4
a=pd.DataFrame(a3)
5
6
b1=[11,22,33,44,55]
7
b2=['ff','gg','c','hh','e']
8
b3={'key':b1, 'v2':b2}
9
b=pd.DataFrame(b3)
10
final result (what I want)
JavaScript
1
5
1
c1=[11,22,33,44,55]
2
c2=['a','b','c','d','e']
3
c3={'key':c1, 'v2':c2}
4
c=pd.DataFrame(c3)
5
but I don’t know how to write python. I tried.
My concept
first, making True, False
JavaScript
1
3
1
i=1
2
a['key'].iloc[i]==b['key']
3
I have 5 bools (F, T, F, F, F)
second, When True value, Change ‘v2’ col of df b but it is not working
JavaScript
1
2
1
b['v2'] = np.where(a['key'].iloc[i]==b['key'], a['v2'], b['v2'])
2
error message :
JavaScript
1
2
1
ValueError: operands could not be broadcast together with shapes (5,) (3,) (5,)
2
I think I have a misunderstanding using ‘np.where’ function.
Advertisement
Answer
we could use Series.map
for mapping key
-> v2
. Set a
‘s key
as index using set_index
. Now, use it in Series.map
JavaScript
1
11
11
1
m = a.set_index('key')['v2']
2
b['v2'] = b['key'].map(m).fillna(b['v2'])
3
4
print(b)
5
# key v2
6
# 0 11 a
7
# 1 22 b
8
# 2 33 c
9
# 3 44 d
10
# 4 55 e
11