【发布时间】:2019-08-08 23:47:16
【问题描述】:
我想在 pyspark 中读取一个文件并从中创建一个数据框。它是一个 tsv 文件,其值格式为:
2015-07-22T09:00:28.019143Z "strings with space" "strings with space" ECDHE THRGH
我尝试创建行对象并将其转换为数据框。但我对如何拆分数据和创建列感到困惑。数据包含带空格的字符串。
from pyspark.sql import Row
from pyspark.sql import SparkSession
import re
spark = SparkSession \
.builder \
.appName("Task1") \
.getOrCreate()
sc = spark.sparkContext
# Load a text file and convert each line to a Row.
lines = sc.textFile("file.tsv")
#parts = lines.map(lambda l: l.split(" ")) -- Tried this but it doesn't give correct output as there are spaces in strings.
values = lines.map(lambda p: Row(value=re.findall(r'\"(.+?)\"', str(p))[0].replace(" ","")))
理想的结果是如下的数据框:
Timestamp val1 val2
val3 val4
2015-07-22T09:00:28.019143Z strings with space strings with space ECDHE THRGH
【问题讨论】:
-
spark.read.option("delimiter", "\t").csv("path to file") -
感谢您的回答。但它没有给出预期的输出。
标签: python-3.x apache-spark pyspark apache-spark-sql