使用isin来模拟sql的IN子句

时间:2018-03-23 14:15:00

标签: python pyspark apache-spark-sql

我有2个数据帧

df1 = sqlContext.createDataFrame(sc.parallelize([(1,'a'),(2,'b'),(3,'c'),(10,'z')]),['id','value'])
df2 = sqlContext.createDataFrame(sc.parallelize([(1,'x'),(2,'y')]),['id','value'])

>>> df1.show()
+---+-----+
| id|value|
+---+-----+
|  1|    a|
|  2|    b|
|  3|    c|
| 10|    z|
+---+-----+

我想模拟select df1.* from df1 where df1.id in (select df2.id from df2)。如何使用isin

进行操作

我尝试了一些但没有工作,这意味着我错过了一些重要的事情。

df1.where(col('id').isin(df2['id']))

df1.where(col('id').isin(*df2.id)).show() //isin() argument after * must be a sequence, not Column

df1.where(col('id').isin(tuple(df2.id))) //Column is not iterable

2 个答案:

答案 0 :(得分:3)

您需要拥有一个本地集合才能使用isin,同时分发数据框列。或者,您可以使用inner join过滤数据框:

df1.join(df2.select('id').dropDuplicates(), ['id']).show()
+---+-----+
| id|value|
+---+-----+
|  1|    a|
|  2|    b|
+---+-----+

答案 1 :(得分:1)

您也可以使用pyspark-sql提供的确切查询:

AVD Manager