Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyspark substring and aggregation

I am new to Spark and I've got a csv file with such data:

date,            accidents, injured
2015/20/03 18:00    15,          5
2015/20/03 18:30    25,          4
2015/20/03 21:10    14,          7
2015/20/02 21:00    15,          6

I would like to aggregate this data by a specific hour of when it has happened. My idea is to Substring date to 'year/month/day hh' with no minutes so I can make it a key. I wanted to give average of accidents and injured by each hour. Maybe there is a different, smarter way with pyspark?

Thanks guys!

like image 380
sampak Avatar asked Nov 29 '25 20:11

sampak


1 Answers

Well, it depends on what you're going to do afterwards, I guess.

The simplest way would be to do as you suggest: substring the date string and then aggregate:

data = [('2015/20/03 18:00', 15, 5), 
    ('2015/20/03 18:30', 25, 4),
    ('2015/20/03 21:10', 14, 7),
    ('2015/20/02 21:00', 15, 6)]
df = spark.createDataFrame(data, ['date', 'accidents', 'injured'])

df.withColumn('date_hr',
              df['date'].substr(1, 13)
     ).groupby('date_hr')\
      .agg({'accidents': 'avg', 'injured': 'avg'})\
      .show()

If you, however, want to do some more computation later on, you can parse the data to a TimestampType() and then extract the date and hour from that.

import pyspark.sql.types as typ
from pyspark.sql.functions import col, udf
from datetime import datetime

parseString =  udf(lambda x: datetime.strptime(x, '%Y/%d/%m %H:%M'),   typ.TimestampType())
getDate =  udf(lambda x: x.date(), typ.DateType())
getHour = udf(lambda x: int(x.hour), typ.IntegerType())

df.withColumn('date_parsed', parseString(col('date'))) \
    .withColumn('date_only', getDate(col('date_parsed'))) \
    .withColumn('hour', getHour(col('date_parsed'))) \
    .groupby('date_only', 'hour') \
    .agg({'accidents': 'avg', 'injured': 'avg'})\
    .show()
like image 60
TDrabas Avatar answered Dec 01 '25 10:12

TDrabas