python - 查找 PySpark 中给定周内的行数

标签 python pandas apache-spark-sql pyspark

我有一个 PySpark 数据框,下面给出了其中的一小部分:

+------+-----+-------------------+-----+
|  name| type|          timestamp|score|
+------+-----+-------------------+-----+
| name1|type1|2012-01-10 00:00:00|   11|
| name1|type1|2012-01-10 00:00:10|   14|
| name1|type1|2012-01-10 00:00:20|    2|
| name1|type1|2012-01-10 00:00:30|    3|
| name1|type1|2012-01-10 00:00:40|   55|
| name1|type1|2012-01-10 00:00:50|   10|
| name5|type1|2012-01-10 00:01:00|    5|
| name2|type2|2012-01-10 00:01:10|    8|
| name5|type1|2012-01-10 00:01:20|    1|
|name10|type1|2012-01-10 00:01:30|   12|
|name11|type3|2012-01-10 00:01:40|  512|
+------+-----+-------------------+-----+

对于选定的时间窗口(例如 1 week 的窗口),我想找出 score 有多少个值(比如 num_values_week )每个 name 都有。即score有多少个值那里有name1之间2012-01-10 - 2012-01-16 ,然后在2012-01-16 - 2012-01-23之间等等(对于所有其他名称也是如此,例如name2等等。)

我想将此信息转换到新的 PySpark 数据框中,该数据框将包含列 name , type , num_values_week 。我怎样才能做到这一点?

上面给出的 PySpark 数据框可以使用以下代码片段创建:

from pyspark.sql import *
import pyspark.sql.functions as F

df_Stats = Row("name", "type", "timestamp", "score")

df_stat1 = df_Stats('name1', 'type1', "2012-01-10 00:00:00", 11)
df_stat2 = df_Stats('name2', 'type2', "2012-01-10 00:00:00", 14)
df_stat3 = df_Stats('name3', 'type3', "2012-01-10 00:00:00", 2)
df_stat4 = df_Stats('name4', 'type1', "2012-01-17 00:00:00", 3)
df_stat5 = df_Stats('name5', 'type3', "2012-01-10 00:00:00", 55)
df_stat6 = df_Stats('name2', 'type2', "2012-01-17 00:00:00", 10)
df_stat7 = df_Stats('name7', 'type3', "2012-01-24 00:00:00", 5)
df_stat8 = df_Stats('name8', 'type2', "2012-01-17 00:00:00", 8)
df_stat9 = df_Stats('name1', 'type1', "2012-01-24 00:00:00", 1)
df_stat10 = df_Stats('name10', 'type2', "2012-01-17 00:00:00", 12)
df_stat11 = df_Stats('name11', 'type3', "2012-01-24 00:00:00", 512)

df_stat_lst = [df_stat1 , df_stat2, df_stat3, df_stat4, df_stat5, 
            df_stat6, df_stat7, df_stat8, df_stat9, df_stat10, df_stat11]
df = spark.createDataFrame(df_stat_lst)

最佳答案

类似这样的事情:

from pyspark.sql.functions import weekofyear, count

df = df.withColumn( "week_nr", weekofyear(df.timestamp) ) # create the week number first
result = df.groupBy(["week_nr","name"]).agg(count("score")) # for every week see how many rows there are

关于python - 查找 PySpark 中给定周内的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58731643/

相关文章:

python - 如何使用带有 boolean 数组的 np.infs 将数组的所有索引归零?

python - pandas:如何限制 str.contains 的结果?

Python/Tensorflow - reshape 的输入是一个具有 92416 个值的张量,但请求的形状需要 2304 的倍数

python - Pandas - 在数据框中添加一个标志列

scala - 在 Spark Scala 中编码时出现 ArrayIndexOutOfBoundsException

json - 将 JSON 文件读入 Spark 数据集并从单独的 Map 添加列

python - 使用管道在进程之间传输 Python 对象时的字节限制?

python - 给定值的最近值

python - 计算每组中 NaN 的数量

json - 使用 sparksql 访问嵌套 json 数据的子字段