如何检查一个数据框中的值是否存在于另一数据框中的键中

时间:2019-02-06 10:44:18

标签: python pandas dataframe

我有两个数据框:

df_1:

         Letters Boolean
          a         Nan
          b         Nan
          c         Nan

df_2:

 a     b     d
 2.7   1.2   3.6
 1      2     3

如何检查df_2.keys()中是否存在df_1 ['letters']。如果存在,我希望布尔值采用值“ x”: 像这样:

     Letters Boolean
      a         x
      b         x
      c         Nan

我尝试使用此代码:

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

2 个答案:

答案 0 :(得分:1)

您需要:

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

答案 1 :(得分:1)

numpy.whereisin一起使用:

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