python - Pyspark 为包含时间范围的记录创建多行

标签 python pyspark timestamp

我有一个如下所示的数据框。

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 = 1578End = 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/

相关文章:

python - 将 unix 时间戳更改为不同的时区

apache-spark - 我怎么知道我的 Spark 工作是否在进行中?

python - 如何修复 Elasticsearch 中的错误 "failed to parse date field "

r - 查找两个数据帧之间最接近的时间戳,并在时间差 < 60 秒时合并不同的列

Python - 在列中编写列表列表

python - 按列索引 Pandas 数据框重命名列

python - Pandas 中的列到行

python - Pyspark Dataframe 上的 Pivot String 列

Python Pyspark : Filter for 1 Day Before Current Date Using F. current_date()

python - 在Python中转换 "yyyy-MM-dd' T'HH :mm:ss. SSSZ"格式的时间戳