IIU C, вы можете использовать pyspark.ml.feature. CountVectorizer , чтобы помочь создать нужный вектор. Предположим, что df1 является первым фреймом данных (user, itemId и date), а df2 - вторым фреймом данных (itemId и index):
from pyspark.ml.feature import CountVectorizerModel
from pyspark.sql.functions import collect_set
df3 = df1.groupby('user').agg(collect_set('itemId').alias('items_arr'))
# set up the vocabulary from the 2nd dataframe and then create CountVectorizerModel from this list
# set binary=True so that this is doing the same as OneHotEncoder
voc = [ r.itemId for r in df2.select('itemId').sort('index').collect() ]
model = CountVectorizerModel.from_vocabulary(voc, inputCol='items_arr', outputCol='items_vec', binary=True)
df_new = model.transform(df3)
df_new.show(truncate=False)
+----+------------------------------+-------------------------+
|user|items_arr |items_vec |
+----+------------------------------+-------------------------+
|3 |[10005903, 12632813] |(4,[1,2],[1.0,1.0]) |
|1 |[10005903, 12458442, 10005880]|(4,[0,1,3],[1.0,1.0,1.0])|
|2 |[10005903, 12632813] |(4,[1,2],[1.0,1.0]) |
+----+------------------------------+-------------------------+
Это создает SparseVector, если вам нужен столбец ArrayType, вам потребуется udf :
from pyspark.sql.functions import udf
udf_to_array = udf(lambda v: [*map(int, v.toArray())], 'array<int>')
df_new.withColumn('interactions', udf_to_array('items_vec')).show(truncate=False)
+----+------------------------------+-------------------------+------------+
|user|items_arr |items_vec |interactions|
+----+------------------------------+-------------------------+------------+
|3 |[10005903, 12632813] |(4,[1,2],[1.0,1.0]) |[0, 1, 1, 0]|
|1 |[10005903, 12458442, 10005880]|(4,[0,1,3],[1.0,1.0,1.0])|[1, 1, 0, 1]|
|2 |[10005903, 12632813] |(4,[1,2],[1.0,1.0]) |[0, 1, 1, 0]|
+----+------------------------------+-------------------------+------------+