How to check if a value in one dataframe is present in keys in the other dataframe

主宰稳场 提交于 2021-02-13 17:38:08

问题


I have two dataframes:

df_1:

         Letters Boolean
          a         Nan
          b         Nan
          c         Nan

df_2:

 a     b     d
 2.7   1.2   3.6
 1      2     3

How do I check if df_1['letters'] is present in df_2.keys(). If it is present, I want boolean to take the value 'x': Something like:

     Letters Boolean
      a         x
      b         x
      c         Nan

I tried using this code:

for x in df_1['letters']:
   if x in df_2.keys():
     df_1['Boolean']='x'

回答1:


Use numpy.where with isin:

df1['Boolean'] = np.where(df1['Letters'].isin(df2.columns), 'x', np.nan)



回答2:


You need :

df1['Boolean']=df1.Letters.isin(df2.columns).map({True:'x',False:np.nan})
print(df1)

  Letters Boolean
0       a       x
1       b       x
2       c     NaN


来源:https://stackoverflow.com/questions/54551692/how-to-check-if-a-value-in-one-dataframe-is-present-in-keys-in-the-other-datafra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!