【问题标题】:How to check if a value in one dataframe is present in keys in the other dataframe如何检查一个数据框中的值是否存在于另一个数据框中的键中
【发布时间】:2021-05-07 17:58:13
【问题描述】:

我有两个数据框:

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_1['letters'] 是否存在于 df_2.keys() 中。如果它存在,我希望布尔值取值'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'

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    numpy.whereisin 一起使用:

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

    【讨论】:

      【解决方案2】:

      你需要:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 2021-09-06
        • 2021-12-25
        • 2021-09-06
        相关资源
        最近更新 更多