如何在 Pyspark 中计算模数?

6 apache-spark apache-spark-sql pyspark pyspark-dataframes

我是 Spark 世界的新手,我想在 Pyspark 中计算一个带有整数模的额外列。我没有在内置运算符中找到这个运算符。

有谁有想法吗?

bla*_*hop 13

您可以简单地%在列之间使用运算符,就像在普通 python 中一样:

from pyspark.sql.functions import col

df = spark.createDataFrame([(6,3), (7, 3), (13,6), (5, 0)], ["x", "y"])
df.withColumn("mod", col("x") % col("y")).show()

#+---+---+----+
#|  x|  y| mod|
#+---+---+----+
#|  6|  3|   0|
#|  7|  3|   1|
#| 13|  6|   1|
#|  5|  0|null|
#+---+---+----+
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用带有 SQL 语法的 spark 内置函数mod%运算符:

from pyspark.sql.functions import expr

# using mod function
df.withColumn("mod", expr("mod(x, y)")).show()

# using SQL %
df.withColumn("mod", expr("x % y")).show()
Run Code Online (Sandbox Code Playgroud)

  • 警告其他用户 pyspark 中的取模可能会返回负结果;与 SQL 的行为相同,但与数学定义和 python 行为不同。请参阅:/sf/ask/733094841/ (2认同)