我有一个如下所示的数据框。
A Start End
1 1578 1581
1 1789 1790
2 1800 1802
开始和结束是纪元。 我想每秒创建多行,就像这样
A time
1 1578
1 1579
1 1580
1 1581
1 1789
1 1790
2 1800
2 1801
2 1802
如何在 pyspark 中做到这一点? (无需保留顺序)
谢谢!
最佳答案
这个想法是创建一个列表
,通过包含中间秒
来涵盖整个时间跨度。例如;对于 Start = 1578
和 End = 1581
,我们创建一个列表 [1578,1579,1580,1581]
。要创建此列表,我们首先创建一个 UDF
。获得此列表后,我们 explode它获取所需的数据帧
。
# 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|
+---+----+
关于python - Pyspark 为包含时间范围的记录创建多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918696/