Pyspark DataFrame-使用基于列名而不是字符串值的类似函数

时间:2018-10-03 11:49:00

标签: pyspark pyspark-sql

我正在尝试在具有另一列的列上使用like函数。可以在like函数中使用Column吗?

示例代码:

df['col1'].like(concat('%',df2['col2'], '%'))

错误日志:

py4j.Py4JException: Method like([class org.apache.spark.sql.Column]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
    at py4j.Gateway.invoke(Gateway.java:274)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:2)

您可以使用SQL表达式来代替。由于某种原因,python API不直接支持它。例如:

from pyspark.sql.functions import expr

data = [
    ("aaaa", "aa"),
    ("bbbb", "cc")
]

df = sc.parallelize(data).toDF(["value", "pattern"])
df = df.withColumn("match", expr("value like concat('%', pattern, '%')"))
df.show()

输出以下内容:

+-----+-------+-----+
|value|pattern|match|
+-----+-------+-----+
| aaaa|     aa| true|
| bbbb|     cc|false|
+-----+-------+-----+