Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Arithmetic Functions and Operations in Spark

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

+---+---+
|  x|  y|
+---+---+
|5.0| 11|
|8.0| 20|
|1.0|-33|
+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11| 12|
|8.0| 20| 21|
|1.0|-33|-32|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11| 10|
|8.0| 20| 19|
|1.0|-33|-34|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11| 22|
|8.0| 20| 40|
|1.0|-33|-66|
+---+---+---+

+---+---+-----+
|  x|  y|    z|
+---+---+-----+
|5.0| 11|  5.5|
|8.0| 20| 10.0|
|1.0|-33|-16.5|
+---+---+-----+

Modulus (%)

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33| -3|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33| -3|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33| -3|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33|  2|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33| -3|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33| -3|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|  1|
|8.0| 20|  0|
|1.0|-33|  2|
+---+---+---+

In Scala/Spark, primitive values must be after the operator. It won’t work if the primitive value in a expression is before the arithmetic operator. There are 2 ways to resolve the issue.

  1. Use the lit to create a const column expression.

  2. Reorder the expression to make the primitive value after the operator.

However, in PySpark primitive types can be used before the operator.

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|-10|
|8.0| 20|-19|
|1.0|-33| 34|
+---+---+---+

+---+---+---+
|  x|  y|  z|
+---+---+---+
|5.0| 11|-10|
|8.0| 20|-19|
|1.0|-33| 34|
+---+---+---+