【问题标题】:How to multiply all the columns of the dataframe in pySpark with other single column如何将pySpark中数据框的所有列与其他单列相乘
【发布时间】:2023-03-14 00:39:01
【问题描述】:

我有特定年份从 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()

是否有任何函数/循环可以让我在整个月内获得整个列乘法和新的数据框值?

【问题讨论】:

  • 你的 spark 版本是什么?
  • Spark 版本 2.4.4

标签: dataframe pyspark multiplication


【解决方案1】:

您可以使用 structs 中的 struct 来表达您的逻辑。 structs与column in higher order基本相同,所以我们可以赋值them a name,multiply them by constant,然后使用columnname.*。这样你就不必这样做了withColumn 12 times.你可以把你所有的月份都放在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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多