我正在使用 PySpark 2.1,我需要想出一种方法将我的数据帧写入专门格式的 .txt 文件;所以不是典型的 json 或 csv,而是 CTF 格式(对于 CNTK)。
该文件不能有额外的括号或逗号等。它遵循以下形式:
|label val |features val val val ... val
|label val |features val val val ... val
显示这一点的一些代码可能如下所示:
l = [('Ankit',25),('Jalfaizy',22),('saurabh',20),('Bala',26)]
rdd = sc.parallelize(l)
people = rdd.map(lambda x: Row(name=x[0], age=int(x[1]))).toDF()
people.show(n=4)
def Convert_to_String(r):
return '|label ' + r.name + ' ' + '|features ' + str(r.age) + '\n'
m_p = people.rdd.map(lambda r: Row(Convert_to_String(r)) ).toDF()
m_p.show(n=3)
在上面的例子中,我只想将每一行的每个字符串附加到一个文件中,不带任何额外的字符。
真实数据框相当大;将其拆分为多个文件可能没问题;但如果结果是单个文件会更可取。
任何见解都非常有帮助。
谢谢!
最佳答案
将我的评论转化为答案。
不是将每条记录转换为 Row
并调用 toDF()
,而是将每条记录映射到一个字符串。然后调用 saveAsTextFile()
。
path = 'path/to/output/file'
# depending on your data, you may need to call flatMap
m_p = people.rdd.flatMap(lambda r: Convert_to_String(r))
# now m_p will contain a list of strings that you can write to a file
m_p.saveAsTextFile(path)
您的数据可能会存储在多个文件中,但您可以从命令行将它们连接在一起。该命令看起来像这样:
hadoop fs -cat path/to/output/file/* > combined.txt
关于python - 将 PySpark DF 写入专用格式的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47557822/