问题
I have a PySpark dataframe, a small portion of which is given below:
+------+-----+-------------------+-----+
| 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|
+------+-----+-------------------+-----+
For a chosen time window (say windows of 1 week
) , I want to find out how many values of score
(say num_values_week
) are there for every name
. That is, how many values of score
are there for name1
between 2012-01-10 - 2012-01-16
, then between 2012-01-16 - 2012-01-23
and so forth (and same for all other names, like name2
and so on.)
I want to have cast this information in new PySpark data frame that will have the columns name
, type
, num_values_week
. How can I do this?
The PySpark dataframe given above can be created using the following code snippet:
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)
回答1:
Something like this:
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
来源:https://stackoverflow.com/questions/58731643/find-number-of-rows-in-a-given-week-in-pyspark