【发布时间】:2021-04-27 08:56:37
【问题描述】:
我想计算从 X 到 Y 的百分比变化。我在这里查看了https://www.calculatorsoup.com/calculators/algebra/percent-change-calculator.php,可以看到它可以计算为:
(v2 - v1) / v1 * 100
所以我在 PySpark 和标准 Python 中都应用了这个:
#formula: (v2 - v1) / v1 * 100
data = [(1, 19360, 49387), (1, 4189, -3039)]
df = spark.createDataFrame(data = data, schema = ["id", "february_sales", "january_sales"])
df.show()
+---+--------------+-------------+
| id|february_sales|january_sales|
+---+--------------+-------------+
| 1| 19360| 49387|
| 1| 4189| -3039|
+---+--------------+-------------+
df = df.withColumn('percent_change', (sf.col('february_sales') - sf.col('january_sales')) / sf.col('january_sales') * 100)
df.show()
+---+--------------+-------------+------------------+
| id|february_sales|january_sales| percent_change|
+---+--------------+-------------+------------------+
| 1| 19360| 49387|-60.79940065199344|
| 1| 4189| -3039|-237.8413951957881|
+---+--------------+-------------+------------------+
feb = 4189
jan = -3039
print((feb - jan)/ jan * 100)
-237.8413951957881
也许我遗漏了一些明显的东西,但是当我将 v1 = -3039,v2 = 4189 插入百分比变化计算器(https://www.omnicalculator.com/math/percentage-change,https://www.calculatorsoup.com/calculators/algebra/percent-change-calculator.php)时,我得到 + 237%。为什么在 Python / PySpark 中我得到 -237%?
【问题讨论】:
标签: python-3.x apache-spark-sql