我正在使用下面的代码片段使用spark上下文读取一些示例文件
>>> textFile = sc.textFile("hdfs:///user/hive/warehouse/sample.txt")
>>> textFile.flatMap(lambda word:word.split(" ")).collect()
假设这会产生类似下面的输出
[u'hi', u'there,', u'I', u'am', u'working', u'on', u'something', u'random.']
现在,我正在使用下面的代码片段使用数据帧读取一些示例文件,然后尝试转换为rdd并像以前一样应用平面地图
>>> df = spark.read.text("hdfs:///user/hive/warehouse/sample.txt")
>>> df.rdd.flatMap(lambda word:word.split(" ")).collect()
此操作失败,并带有错误拆分属性。
我继续使用下面的代码片段检查df.rdd和textFile的数据类型
>>> type(df.rdd)
<class 'pyspark.rdd.RDD'>
>>> type(textFile)
<class 'pyspark.rdd.RDD'>
两者相同。
现在,当我使用下面的代码片段检查这些Rdd的单个元素的类型时。我正在观察差异。
>>> textFile.map(lambda x:type(x)).collect()
[<type 'unicode'>]
>>> df.rdd.map(lambda x:type(x)).collect()
[<class 'pyspark.sql.types.Row'>]
为什么会有差异
答案 0 :(得分:2)
将df转换为rdd后,应将其转换为列表
>>> textFile = sc.textFile("hdfs://localhost:8020/test/ali/sample.txt")
>>> textFile.flatMap(lambda word:word.split(" ")).collect()
['hi', 'there,', 'I', 'am', 'working', 'on', 'something', 'random.']
>>>
>>> df = spark.read.text("hdfs://localhost:8020/test/ali/sample.txt")
>>> df.rdd.flatMap(lambda x: list(x)).flatMap(lambda word:word.split(" ")).collect()
['hi', 'there,', 'I', 'am', 'working', 'on', 'something', 'random.']