pyspark parse fixed width text file

风格不统一 提交于 2019-11-28 13:52:49

Spark's substr function can handle fixed-width columns, for example:

df = spark.read.text("/tmp/sample.txt")
df.select(
    df.value.substr(1,3).alias('id'),
    df.value.substr(4,8).alias('date'),
    df.value.substr(12,3).alias('string'),
    df.value.substr(15,4).cast('integer').alias('integer')
).show()

will result in:

+---+--------+------+-------+
| id|    date|string|integer|
+---+--------+------+-------+
|001|01292017|   you|   1234|
|002|01302017|    me|   5678|
+---+--------+------+-------+

Having splitted columns you can reformat and use them as in normal spark dataframe.

shubham singh

I want to automate this process as number of columns will be different for different files

df.value.substr(1,3).alias('id'),
df.value.substr(4,8).alias('date'), 
df.value.substr(12,3).alias('string'),
df.value.substr(15,4).cast('integer').alias('integer')

I created a Python function to generate this on the basis of schema file but now when I am appending it with df.select("my automated string").show it's throwing an error analysis exception

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