我有特定年份从 1 月到 12 月所有月份的数据,我有一列说“常量”,我需要将该常量列值与 spark 中从 1 月到 12 月的所有列数据相乘。例如,我有以下数据:
JAN FEB MAR...DEC Constant
City1 160 158 253 391 12
City2 212 27 362 512 34
City3 90 150 145 274 56
乘法后,我想用值新建/替换数据框:
JAN FEB MAR ....DEC
City1 192 1896 3036 1656
City2 7208 918 12308 8092
City3 504 280 8120 2464
我可以使用代码一次按一列来完成:
Df.select("JAN","CONSTANT").withColumn("JAN",col('JAN') * col ('CONSTANT')).show()
是否有任何函数/循环可以让我整个月获得整个列乘法和新数据帧值?
最佳答案
您可以使用 structs
的 struct
表达您的逻辑。结构基本上与高阶列
相同,因此我们可以为它们分配一个名称
,将它们乘以常数
,然后使用 columnname.*
选择它们。这样您就不必执行 withColumn 12 次。
您可以将所有月份都放在 listofmonths
中。
df.show() #sampledata
#+-----+---+---+---+---+--------+
#| City|JAN|FEB|MAR|DEC|Constant|
#+-----+---+---+---+---+--------+
#|City1|160|158|253|391| 12|
#|City2|212| 27|362|512| 34|
#|City3| 90|150|145|274| 56|
#+-----+---+---+---+---+--------+
listofmonths=['JAN','FEB','MAR','DEC']
from pyspark.sql import functions as F
df.withColumn("arr", F.struct(*[(F.col(x)*F.col('Constant')).alias(x) for x in listofmonths]))\
.select("City","arr.*")\
.show()
#+-----+----+----+-----+-----+
#| City| JAN| FEB| MAR| DEC|
#+-----+----+----+-----+-----+
#|City1|1920|1896| 3036| 4692|
#|City2|7208| 918|12308|17408|
#|City3|5040|8400| 8120|15344|
#+-----+----+----+-----+-----+
您也可以像这样使用 df.columns
而不是 listofmonths
:
from pyspark.sql import functions as F
df.withColumn("arr", F.struct(*[(F.col(x)*F.col('Constant')).alias(x) for x in df.columns if x!='City' and x!='Constant']))\
.select("City","arr.*")\
.show()
关于dataframe - 如何将pySpark中数据框的所有列与其他单列相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61529955/