这个想法是创建一个list,通过包含中间seconds 来涵盖整个时间跨度。例如;对于Start = 1578 和End = 1581,我们创建一个列表[1578,1579,1580,1581]。要创建此列表,我们首先创建一个UDF。一旦得到这个列表,我们就explode它来获取所需的dataframe。
# Creating the DataFrame
values = [(1,1578,1581),(1,1789,1790),(2,1800,1802)]
df = sqlContext.createDataFrame(values,['A','Start','End'])
df.show()
+---+-----+----+
| A|Start| End|
+---+-----+----+
| 1| 1578|1581|
| 1| 1789|1790|
| 2| 1800|1802|
+---+-----+----+
# Import requisite packages
from pyspark.sql.functions import udf, col, explode, array, struct
from pyspark.sql.types import ArrayType, StructType, StructField, IntegerType
#Creating UDFs below to create a list.
def make_list(start,end):
return list(range(start,end+1))
make_list_udf = udf(make_list,ArrayType(IntegerType()))
#Creating Lists of seconds finally.
df = df.withColumn('my_list',make_list_udf(col('Start'),col('End'))).drop('Start','End')
df.show(truncate=False)
+---+------------------------+
|A |my_list |
+---+------------------------+
|1 |[1578, 1579, 1580, 1581]|
|1 |[1789, 1790] |
|2 |[1800, 1801, 1802] |
+---+------------------------+
#Exploding the Lists
df = df.withColumn('time', explode('my_list')).drop('my_list')
df.show()
+---+----+
| A|time|
+---+----+
| 1|1578|
| 1|1579|
| 1|1580|
| 1|1581|
| 1|1789|
| 1|1790|
| 2|1800|
| 2|1801|
| 2|1802|
+---+----+