PySpark - 根据另一列中引用的列名称创建列

mor*_*nor 3 python apache-spark-sql pyspark

我对 Spark 很陌生,无法让它工作...希望有一种简单的方法可以做到这一点...我想要做的最好由下表描述:(我需要获得“必填”栏)

    colA    colB    colC    ref     required
1   a1        b1    c1      colA     a1
2   a2        b2    c2      colA     a2
3   a3        b3    c3      colB     b3
4   a4        b4    c4      colB     b4
5   a5        b5    c5      colC     c5
6   a6        b6    c6      colC     c6
Run Code Online (Sandbox Code Playgroud)

上面只是一个例子 - 在真实的例子中我有 >50 列,所以做条件是行不通的......

我知道这可以在 pandas 中轻松完成,使用以下方法:

df['required'] = df.apply(lambda x: x.loc[x.ref], axis=1)
Run Code Online (Sandbox Code Playgroud)

或者

df['required'] = df.lookup(df.index, df.ref)
Run Code Online (Sandbox Code Playgroud)

有什么建议如何在 PySpark 中执行此操作吗?

Psi*_*dom 8

一种方法是使用whenandcoalesce函数:

import pyspark.sql.functions as F

cols = ['colA', 'colB', 'colC']
df.withColumn('required', F.coalesce(*[F.when(df.ref == c, df[c]) for c in cols])).show()
+----+----+----+----+--------+
|colA|colB|colC| ref|required|
+----+----+----+----+--------+
|  a1|  b1|  c1|colA|      a1|
|  a2|  b2|  c2|colA|      a2|
|  a3|  b3|  c3|colB|      b3|
|  a4|  b4|  c4|colB|      b4|
|  a5|  b5|  c5|colC|      c5|
|  a6|  b6|  c6|colC|      c6|
+----+----+----+----+--------+
Run Code Online (Sandbox Code Playgroud)

基本上,您检查该ref列等于哪个列的名称,并从该列中获取值 -- F.when(df.ref == c, df[c]);这将创建一个列对象列表,当其名称出现在ref列中时,其值将被保留,否则其值为 NULL;然后,通过合并列列表,用有效列值中的值填充 NULL 值。