【问题标题】:Percent Change Formula Gives -% unexpectedly百分比变化公式给出 -% 出乎意料
【发布时间】: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-changehttps://www.calculatorsoup.com/calculators/algebra/percent-change-calculator.php)时,我得到 + 237%。为什么在 Python / PySpark 中我得到 -237%?

【问题讨论】:

    标签: python-3.x apache-spark-sql


    【解决方案1】:

    在您共享的第二个链接中,分母被转换为绝对值,您的代码中缺少该值。要复制相同的代码,请检查下面的代码。

    from  pyspark.sql.functions import abs
    df = df.withColumn('percent_change', (df.february_sales - df.january_sales) / abs(df.january_sales) * 100)
    df.show()
    

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 2017-08-04
      • 2014-09-11
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 2018-07-14
      相关资源
      最近更新 更多