[英]How to replace values in DataFrame with values from second DataFrame with condition that it selects different column?
I have a two DataFrames.我有两个数据帧。 df1:
df1:
A | B | C
-----|---------|---------|
25zx | b(50gh) | |
50tr | a(70lc) | c(50gh) |
df2: df2:
A | B
-----|-----
25zx | T
50gh | K
50tr | K
70lc | T
I want to replace values in df1.我想替换 df1 中的值。 The row that I'm comparing is df2['A'], but the value that I want to put in to df1 is value from the row df['B'].
我要比较的行是 df2['A'],但我想放入 df1 的值是来自 df['B'] 行的值。
So the final table would look like:所以决赛桌看起来像:
df3: df3:
A | B | C
-----|---------|---------|
T | b(K) | |
K | a(T) | c(K) |
Cast df2
to dict
and use replace
:将
df2
为dict
并使用replace
:
print (df.replace(df2.set_index("A")["B"].to_dict(), regex=True))
A B C
0 T b(K) None
1 K a(T) c(K)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.