from pyspark.sql.functions import col, first, explode, max as max_
result = (
# Here we take exploded rows and for each row check if there
# is a match. We cast to integer (false -> 0, true -> 1)
# and take max (1 if there is any match)
max_((col("fav_item") == col("item")).cast("integer"))
).alias("result")
(df.repartition("user", "item")
# Explode array so we compare item and fav_item
.withColumn("fav_item", explode("fav_items"))
.groupBy("user", "item")
# Aggregate
# we add result and retain fav_items
.agg(result, first("fav_items").alias("fav_items")))
# Imports
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
# First we create a RDD in order to create a dataFrame:
rdd = sc.parallelize([('u1', 1, [1 ,2, 3]), ('u1', 4, [1, 2, 3])])
df = rdd.toDF(['user', 'item', 'fav_items'])
# Print dataFrame
df.show()
# We make an user define function that receives two columns and do operation
function = udf(lambda item, items: 1 if item in items else 0, IntegerType())
df.select('user', 'item', 'fav_items', function(col('item'), col('fav_items')).alias('result')).show()
只是为了好玩,非自定义项解决方案:
所以它只是:
展开
fav_array
:检查
fav_item
=item
(_1
是否是(col("fav_item") == col("item")).cast("integer")
表达式的结果):并将其回滚,保持
user
和item
作为组列,任意fav_items
(都相同)和临时列_1
(0或1)的最大值。不过,我还是要用UDF。
以下代码执行请求的任务。定义了一个用户定义的函数,它接收一个
DataFrame
的两列作为参数。因此,对于每一行,搜索项目是否在项目列表中。如果找到该项,则返回1,否则返回0。结果如下:
相关问题 更多 >
编程相关推荐