Pyspark:如何从表格中提取统计信息?

问题描述 投票:0回答:2

我有一个如下表:

+--------------------+-------------------+-----+
|                  ID|               time|count|
+--------------------+-------------------+-----+
|378101ee32a648ef0...|2020-01-01 11:00:00| 2900|
|ff5d5840742d42beb...|2020-01-01 23:00:00| 1615|
|ff5d5840742d42beb...|2020-01-01 22:00:00| 1589|
|a06f198b200364fb0...|2020-01-01 01:00:00| 1571|
|18991cb9b06c4dbde...|2020-01-01 01:00:00| 1514|
|aaf20cfe4ebc98ca8...|2020-01-01 19:00:00| 1462|
|35e96b1170613db44...|2020-01-01 17:00:00| 1324|
|0eb82275984a3eef0...|2020-01-01 16:00:00| 1305|
|0eb82275984a3eef0...|2020-01-01 17:00:00| 1305|

我想编写一个查询,该查询返回每小时包含与每个ID的count相关的某些统计信息的表

例如,我想要一个类似以下的表:

       time              mean     median     min    max    5thPercentile  95thPercentile
2020-01-01 00:00:00       33        27.5      2    2000       3.4            1300        
2020-01-01 10:00:00       33        27.5      2    2000       2.6            1120
python sql pyspark pyspark-sql
2个回答
0
投票

您可以使用窗口功能和聚合。我认为这可以满足您的要求:

select time,
       avg(count),
       (max(case when tile = 10 then count end) +
        min(case when tile = 11 then count end)
       ) / 11,
       max(case when tile = 1 then count end) as percentile_05,
       max(case when tile = 19 then count end) as percentile_95
from (select t.*,
             ntile(20) over (partition by count) as tile
      from t
     ) t
group by time;

0
投票

使用pyspark.sql创建熊猫的类似DataFrame的对象。

然后您可以调用describe()查看有关数据的统计信息。

文档示例:

>>> df.describe(['age']).show()
+-------+------------------+
|summary|               age|
+-------+------------------+
|  count|                 2|
|   mean|               3.5|
| stddev|2.1213203435596424|
|    min|                 2|
|    max|                 5|
+-------+------------------+
© www.soinside.com 2019 - 2024. All rights reserved.