我想遍历 pyspark 数据框中的每一行,并根据另一列的内容更改一列的值。我将其更改为的值也是基于要更改的列的当前值。
具体来说,我有一列包含 DenseVectors,另一列包含我需要的向量的索引。
或者,我也可以用 DenseVector 中两个值中较大的值替换 DenseVector。
我主要尝试将 F.when() 与 withColumn 结合使用,但我遇到了 F.when() 的第二个元素的问题,因为我想存储向量的正确索引,但不能直接在列上建立索引。
a b
1 DenseVector([0.1, 0.9]) 1.0
2 DenseVector([0.6, 0.4]) 0.0
.
.
.
df = df.withColumn('a', F.when(df.b == 0.0, df.a[0])
.otherwise(df.a[1])
请您参考如下方法:
我能够根据 this question 的答案中找到的信息得出解决方案。 .
Spark 中似乎存在一个错误,它不允许您对 Spark 数据帧中包含的 DenseVectors 进行索引。这可以通过创建一个用户定义的函数来解决,该函数可以像 numpy 数组一样访问元素。
from pyspark.sql import functions as F
from pyspark.sql import types as T
firstelement=F.udf(lambda v:float(v[0]),T.FloatType())
secondelement=F.udf(lambda v:float(v[1]),T.FloatType())
df = df.withColumn('a', F.when(df['b'] == 0.0,
firstelement('a')).otherwise(secondelement('a'))
