这个想法是在 positive 的列中标记行并返回相应列的值。
您可以使用reduce标记列并创建一个新的DataFrame,最后使用concat_ws形成所需的值
@anky 提供的更简洁的解决方案
简洁的解决方案 -
sparkDF.withColumn("GreaterThanZero",F.concat_ws(",",*[F.when(F.col(col)>0,col) for col in to_concat]))\
.select("id","GreaterThanZero").show()
+---+---------------+
| id|GreaterThanZero|
+---+---------------+
|id1| A,D|
|id2| B,D|
|id3| A,B,C|
|id4| A,D|
+---+---------------+
数据准备
input_str = """
id1 1 0 0 2
id2 0 3 0 1
id3 1 2 5 0
id4 4 0 0 1
""".split()
input_values = list(map(lambda x: x.strip() if x.strip() != 'null' else None, input_str))
cols = list(map(lambda x: x.strip() if x.strip() != 'null' else None, "ID A B C D".split()))
n = len(input_values)
n_cols = 5
input_list = [tuple(input_values[i:i+n_cols]) for i in range(0,n,n_cols)]
sparkDF = sql.createDataFrame(input_list, cols)
sparkDF.show()
+---+---+---+---+---+
| ID| A| B| C| D|
+---+---+---+---+---+
|id1| 1| 0| 0| 2|
|id2| 0| 3| 0| 1|
|id3| 1| 2| 5| 0|
|id4| 4| 0| 0| 1|
+---+---+---+---+---+
减少
to_check = ['id','A','B','C','D']
sparkDF_marked = reduce(lambda df
, x: df.withColumn(x,F.when(F.col(x) > 0 ,x).otherwise(None))\
if x != 'id' else df.withColumn(x,F.col(x)) \
,to_check, sparkDF
)
sparkDF_marked.show()
+---+----+----+----+----+
| id| A| B| C| D|
+---+----+----+----+----+
|id1| A|null|null| D|
|id2|null| B|null| D|
|id3| A| B| C|null|
|id4| A|null|null| D|
+---+----+----+----+----+
连接
to_concat = ['A','B','C','D']
sparkDF_marked.select(['id',F.concat_ws(',',*to_concat).alias('GreaterThanZero')]).show()
+---+---------------+
| id|GreaterThanZero|
+---+---------------+
|id1| A,D|
|id2| B,D|
|id3| A,B,C|
|id4| A,D|
+---+---------------+
该解决方案虽然有效,但有一些细微差别需要小心,尤其是 reduce 代码 sn-p 和 to_check 和 to_concat。
to_check 可以很容易地替换为 - sparkDF.columns 用于实际数据,但请告诉我在更大数据集上的性能。