为什么 pyspark 给出错误的方差值?

Why pyspark give the wrong value of variance?

我在 pyspark 中注册了 table。

+--------+-------+--------+------------+---------+-----------------+----------------------+
|order_id|user_id|eval_set|order_number|order_dow|order_hour_of_day|days_since_prior_order|
+--------+-------+--------+------------+---------+-----------------+----------------------+
| 2168274|      2|   prior|           1|        2|               11|                  null|
| 1501582|      2|   prior|           2|        5|               10|                    10|
| 1901567|      2|   prior|           3|        1|               10|                     3|
|  738281|      2|   prior|           4|        2|               10|                     8|
| 1673511|      2|   prior|           5|        3|               11|                     8|
| 1199898|      2|   prior|           6|        2|                9|                    13|
| 3194192|      2|   prior|           7|        2|               12|                    14|
|  788338|      2|   prior|           8|        1|               15|                    27|
| 1718559|      2|   prior|           9|        2|                9|                     8|
| 1447487|      2|   prior|          10|        1|               11|                     6|
| 1402090|      2|   prior|          11|        1|               10|                    30|
| 3186735|      2|   prior|          12|        1|                9|                    28|
| 3268552|      2|   prior|          13|        4|               11|                    30|
|  839880|      2|   prior|          14|        3|               10|                    13|
| 1492625|      2|   train|          15|        1|               11|                    30|
+--------+-------+--------+------------+---------+-----------------+----------------------+

我想计算 days_since_prior_order 的方差,不包括空值。正确的值应该是97.91836734693878,这是hive给的,python。但是我的 pyspark 给我 105.45054945054943.

spark.sql("select variance(days_since_prior_order) from \
(select * from orders where user_id=2 and days_since_prior_order is not null ) ").show()

原始 table 数据类型是正确的。

 |-- order_id: long (nullable = true)
 |-- user_id: long (nullable = true)
 |-- eval_set: string (nullable = true)
 |-- order_number: short (nullable = true)
 |-- order_dow: short (nullable = true)
 |-- order_hour_of_day: short (nullable = true)
 |-- days_since_prior_order: short (nullable = true)

尝试使用以下函数代替 pyspark.sql.functions.variance(col):

pyspark.sql.functions.var_pop(col)

Aggregate function: returns the population variance of the values in a group.

根据你的列数据,var_pop 给出了这个结果:

[Row(var_pop(days_since_prior_order)=97.91836734693877)]

原因是:

  • variance()var_samp() 缩放 1/(N-1)
  • var_pop() 缩放 1/N

选择了 N 个值。

请参阅 population and sample variance 以获得有用的 link。

Here 你会找到 var_pop()

的文档