我有这样的数据框:
id feature value
a aa 0.5
b ab 0.1
a ab 0.2
a cc 0.3
c ab 0.9
b bb 1
我假设特征列中总共有 4 个唯一值,并且所有id可能不对应于所有特征,所以我想要另一个数据帧,其中id将对应于它具有的特征值,否则如果该特征不存在,则为 0。
例如。:
feature_list = ['aa', 'ab', 'cc', 'bb']
id feature_vector
a [0.5, 0.2, 0.3, 0]
b [0, 0.1, 0, 1]
c [0, 0.9, 0, 0]
您可以创建地图并从中提取值。
from pyspark.sql import functions as F
df = spark.createDataFrame(
[('a', 'aa', 0.5),
('b', 'ab', 0.1),
('a', 'ab', 0.2),
('a', 'cc', 0.3),
('c', 'ab', 0.9),
('b', 'bb', 1.0)],
['id', 'feature', 'value'])
feature_list = ['aa', 'ab', 'cc', 'bb']
df = df.groupBy('id').agg(F.map_from_entries(F.collect_set(F.struct('feature', 'value'))).alias('map'))
df = df.withColumn('arr', F.array([F.lit(x) for x in feature_list]))
df = df.select('id', F.expr("transform(arr, x -> coalesce(map[x], 0)) feature_vector"))
df.show()
# +---+--------------------+
# | id| feature_vector|
# +---+--------------------+
# | c|[0.0, 0.9, 0.0, 0.0]|
# | b|[0.0, 0.1, 0.0, 1.0]|
# | a|[0.5, 0.2, 0.3, 0.0]|
# +---+--------------------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句