PySpark: Convert a pair RDD back to a regular RDD

ε祈祈猫儿з 提交于 2019-12-13 01:35:08

问题


Is there any way I can convert a pair RDD back to a regular RDD?

Suppose I get a local csv file, and I first load it as a regular rdd

rdd = sc.textFile("$path/$csv")

Then I create a pair rdd (i.e. key is the string before "," and value is the string after ",")

pairRDD = rdd.map(lambda x : (x.split(",")[0], x.split(",")[1]))

I store the pairRDD by using the saveAsTextFile()

pairRDD.saveAsTextFile("$savePath")

However, as investigated, the stored file will contain some necessary characters, such as "u'", "(" and ")" (as pyspark simply calls toString(), to store key-value pairs) I was wondering if I can convert back to a regular rdd, so that the saved file wont contain "u'" or "(" and ")"? Or any other storage methods I can use to get rid of the unnecessary characters ?


回答1:


Those characters are the Python representation of your data as string (tuples and Unicode strings). You should convert your data to text (i.e. a single string per record) since you use saveAsTextFile. You can use map to convert the key/value tuple into a single value again, e.g.:

pairRDD.map(lambda (k,v): "Value %s for key %s" % (v,k)).saveAsTextFile(savePath)


来源:https://stackoverflow.com/questions/32971315/pyspark-convert-a-pair-rdd-back-to-a-regular-rdd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!