【问题标题】:Filtering out row in Pyspark when there is a word from other table in any column当任何列中有来自其他表的单词时,过滤掉 Pyspark 中的行
【发布时间】:2016-12-26 23:11:12
【问题描述】:

我是 pyspark 的新手,我想写一个类似的查询,

select * from table1 where column like '%word1%' 我们用 sql 或 hive 写的。

我正在编写以下命令,

data = sqlCtx.sql('select * from table1 where column like '%word1%')

但是我遇到了一些错误,例如,

NameError: name 'word1' is not defined

我最理想的情况是,

select word_name from table2;

将给出一个单词列表,每当这些单词出现在 table1 的任何列中时,我想过滤掉这些条目并给出剩余的行并将其放入数据框中。

谁能帮我做这件事?

谢谢

【问题讨论】:

  • 不应该是:"select * from table1 where column like '%word1%'")?
  • @Dair 哦,是的.. 我的错!但是你能帮我解决第二个要求,我们可以从 table2 中获取单词并将其过滤掉吗?
  • 不好意思,对spark中的SQL模块不太了解。看起来这可能是一个快速修复。

标签: python sql apache-spark dataframe pyspark


【解决方案1】:

这里可能更简单:

input_list = tbl1.select('col1').distinct().rdd.map(lambda x: x).collect()
tbl2.where(col('col2').isin(input_list) == False)

【讨论】:

    【解决方案2】:

    好吧,“like”函数在 pyspark 中工作得很好,就像在 SQL 中一样。使用 DataFrame API 和 SQL API。 例子:

    import statsmodels.api as sm
    duncan_prestige = sm.datasets.get_rdataset("Duncan", "car")
    df = sqlContext.createDataFrame(duncan_prestige.data.reset_index())
    
        index   type    income  education   prestige
    0   accountant  prof    62  86  82
    1   pilot   prof    72  76  83
    2   architect   prof    75  92  90
    3   author  prof    55  90  76
    

    数据帧 API:

    df.filter(df['index'].like('%ilo%')).toPandas()
    
        index   type    income  education   prestige
    0   pilot   prof    72  76  83
    

    或者使用 SQL

    df.registerTempTable('df')
    sqlContext.sql("select * from df d where d.index like '%ilo%' ").toPandas()
    

    and with join(愚蠢,但为了证明这一点)

    qry = """
    select d1.* 
    from df d1 join df d2 
        on ( d1.index  = d2.index)
    where d1.index like '%ilo%' and d2.index like concat('%', d1.index , '%')
    """
    sqlContext.sql(qry).toPandas()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 2012-11-19
      • 1970-01-01
      相关资源
      最近更新 更多