简体   繁体   English

如何在选择不同列的条件下用第二个 DataFrame 中的值替换 DataFrame 中的值?

[英]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 :df2dict并使用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.

相关问题 如何根据第二个 Dataframe 值的条件替换 Dataframe 列值 - How to Replace Dataframe Column Values Based on Condition of Second Dataframe Values 如何用第二个 DataFrame 中的值替换一个 DataFrame 中的列中的值,两者在 Python Pandas 中都有主键? - How to replace values in column in one DataFrame by values from second DataFrame both have major key in Python Pandas? 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python 如何根据具有一系列值的条件替换 pd 数据框列中的值? - How to Replace values in a pd dataframe column based on a condition with a range of values? 根据条件用不同的替换字典替换熊猫数据框列中的值 - Replace values in pandas dataframe column with different replacement dict based on condition 通过将另一列与第二个DataFrame进行比较,替换一列中的值 - Replace values from one column by comparing another column to a second DataFrame 如何使用 Pandas 使用来自第二个数据帧但依赖于当前数据帧中不同现有列的值填充新列 - How To Fill New Column With Values From Second Dataframe but Dependent on Different Existing Column in Current Dataframe using Pandas 根据条件替换数据框列中的值 - Replace values in a dataframe column based on condition 根据条件替换列中的值,然后返回数据框 - Replace values in column based on condition, then return dataframe 通过条件从第二个数据帧的值修复数据帧值 - Fix dataframe values by values from second dataframe with condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM