apache-spark - 将 PySpark 数组列乘以标量

标签 apache-spark pyspark apache-spark-sql multiplication

我正在尝试将一个数组类型的列乘以一个标量。此标量也是来自同一 PySpark 数据帧的值。

例如,我有这个数据框:

df = sc.parallelize([([1, 2],3)]).toDF(["l","factor"])
+------+------+
|     l|factor|
+------+------+
|[1, 2]|     3|
+------+------+

我想实现的是:

+------+------+
|     l|factor|
+------+------+
|[3, 6]|     3|
+------+------+

这是我试过的:

df.withColumn("l", lit("factor") * df.l)

它返回类型不匹配错误。 如何将数组类型的列乘以数字?

最佳答案

spark-2.4 使用 transform

spark.sql(""" select l, factor, transform(l,x -> x * factor) as result from tmp """).show(10,False)
#+------+------+------+
#|l     |factor|result|
#+------+------+------+
#|[1, 2]|3     |[3, 6]|
#+------+------+------+

使用 dataframe API:

df.withColumn("res",expr("""transform(l,x -> x*factor)""")).show()
#+------+------+------+
#|     l|factor|   res|
#+------+------+------+
#|[1, 2]|     3|[3, 6]|
#+------+------+------+

关于apache-spark - 将 PySpark 数组列乘以标量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62478107/

相关文章:

java - 通过在 Apache Spark Java 中搜索数据集的列标题来查找列索引

dataframe - Spark Scala 中减去两个数据帧中的列以获得差异

python - 如何访问 Spark 稀疏向量元素

arrays - 使用一系列数字范围创建新列

java - Spark 采样 - 比使用完整的 RDD/DataFrame 快多少

arrays - 两个数组成员的乘法

python - 如何在 PySpark 中读取从 Spark 编写的 Parquet ?

python - 在 pyspark 中将数据框保存到本地驱动器上的 JSON 文件

python - 在 pySpark 中使用 paramGrid 从 CrossValidator 中提取结果

python - org.apache.spark.SparkException : Unseen label with TrainValidationSplit