[英]PySpark join dataframes with LIKE
我尝试使用 LIKE 表达式连接数据帧,其中条件( LIKE的内容)存储在列中。 PySpark 2.3有可能吗?
Source dataframe:
+---------+----------+
|firstname|middlename|
+---------+----------+
| James| |
| Michael| Rose|
| Robert| Williams|
| Maria| Anne|
+---------+----------+
Second dataframe
+---------+----+
|condition|dest|
+---------+----+
| %a%|Box1|
| %b%|Box2|
+---------+----+
Expected result:
+---------+----------+---------+----+
|firstname|middlename|condition|dest|
+---------+----------+---------+----+
| James| | %a%|Box1|
| Michael| Rose| %a%|Box1|
| Robert| Williams| %b%|Box2|
| Maria| Anne| %a%|Box1|
+---------+----------+---------+----+
让我在下面的示例中重现该问题。 让我们创建一个示例 dataframe:
from pyspark.sql.types import StructType,StructField, StringType, IntegerType
data = [("James",""),
("Michael","Rose"),
("Robert","Williams"),
("Maria","Anne")
]
schema = StructType([ \
StructField("firstname",StringType(),True), \
StructField("middlename",StringType(),True)
])
df = spark.createDataFrame(data=data,schema=schema)
df.show()
第二个:
mapping = [("%a%","Box1"),("%b%","Box2")]
schema = StructType([ \
StructField("condition",StringType(),True), \
StructField("dest",StringType(),True)
])
map = spark.createDataFrame(data=mapping,schema=schema)
map.show()
如果我是对的,在连接数据帧期间不可能使用 LIKE,所以我创建了一个 crossJoin 并尝试使用类似的过滤器,但是是否可以从列中获取内容,而不是固定字符串? 这是无效的语法,但我正在寻找另一种解决方案:
df.crossJoin(map).filter(df.firstname.like(map.condition)).show()
任何表达式都可以用作连接条件。 没错,对于 DataFrame API 这样的函数参数只能是str
,不能是Column
,所以你不能有col("firstname").like(col("condition"))
。 然而 SQL 版本没有这个限制所以你可以利用expr :
df.join(map, expr("firstname like condition")).show()
或者只是简单的 SQL:
df.createOrReplaceTempView("df")
map.createOrReplaceTempView("map")
spark.sql("SELECT * FROM df JOIN map ON firstname like condition").show()
两者都返回相同的结果:
+---------+----------+---------+----+
|firstname|middlename|condition|dest|
+---------+----------+---------+----+
| James| | %a%|Box1|
| Michael| Rose| %a%|Box1|
| Robert| Williams| %b%|Box2|
| Maria| Anne| %a%|Box1|
+---------+----------+---------+----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.