Pandas 根据条件从另一个df获取值

Pandas 根据条件从另一个df获取值,pandas,numpy,dataframe,Pandas,Numpy,Dataframe,我有两个df df1: 和df2: id2 X Y Magic 2 3 Sand 2 3 Cooper 1 2 Dean 1 2 如果Cond=“sick”和df[“id”]=df[“id2],我想更新df1中的x值 要获取新的df1,请执行以下操作: ID X Y Cond Johnson 2 3 fine Sand 2 3 sick Cooper 1 2 fine Nelson 1 2 fine Peterson

我有两个df

df1:

和df2:

id2      X Y 
Magic    2 3 
Sand     2 3 
Cooper   1 2 
Dean     1 2 
如果Cond=“sick”和df[“id”]=df[“id2],我想更新df1中的x值 要获取新的df1,请执行以下操作:

ID       X Y Cond
Johnson  2 3 fine
Sand     2 3  sick
Cooper   1 2 fine
Nelson   1 2 fine
Peterson 4 5 fine
我试过:

df1["x"] = np.where((df["cond"]=="sick")& (df1["id"]==df2["id2"]),df2["x"],"")
但它不起作用。我得到一个错误:

ValueError: Can only compare identically-labeled Series objects


谢谢

首先通过以下方式将两个
ID
列转换为可能匹配选定行的索引值:


您可以使用dataframes的
where()
方法,而不是numpy的
where
函数。代码如下所示:

df1.loc[:,["X", "Y"]] = df1.loc[:,["X", "Y"]].where(df1["Cond"]!="sick",df2.loc[:,["X", "Y"]])

谢谢,但它不起作用。当运行此代码时,我得到以下错误:#将我从另一个代码中切掉。知道吗?检查列名称的大小写。我使用大写字母表示“X”和“Y”
df11 = df1.set_index('ID')
df22 = df2.set_index('id2')

df11.loc[df11["Cond"]=="sick", ['X','Y']] = df22[['X','Y']]
df = df11.reset_index()
print (df)
         ID  X  Y  Cond
0   Johnson  2  3  fine
1      Sand  2  3  sick
2    Cooper  1  2  fine
3    Nelson  1  2  fine
4  Peterson  4  5  fine
df1.loc[:,["X", "Y"]] = df1.loc[:,["X", "Y"]].where(df1["Cond"]!="sick",df2.loc[:,["X", "Y"]])