我有一個 CSV(;作為分隔符),其中有幾列如下所示:
c1;c2;c3
1;foo";"bar;10
2;foo;20
3;bar;30
...
制作檔案的";"人使用它來判斷它;不是分隔符。
我需要閱讀檔案,spark.read.options(delimiter=';',header=True,inferSchema=True).csv('path\to\file)
但我得到:
c1 | c2 | c3
1 | foo"| bar;10
2 | foo | 20
3 | bar | 30
...
我需要的一個:
c1 c2 c3
1 foo;bar 10
2 foo 20
3 bar 30
...
有沒有辦法改變delimiter=';'以獲得我需要的資料集?我無法更改分隔符或“;”。
uj5u.com熱心網友回復:
你可以:
- 將您的 CSV 作為文本檔案讀取
- 全部替換
;為| - 全部替換
"|"為; - 分開
|
rdd = spark.sparkContext.textFile(r'your\path\test.csv')
rdd = rdd.map(lambda line: line.replace(';', '|').replace('"|"', ';').split('|'))
header = rdd.first()
df = rdd.filter(lambda line: line != header).toDF(header)
df.show()
# --- ------- ---
# | c1| c2| c3|
# --- ------- ---
# | 1|foo;bar| 10|
# | 2| foo| 20|
# | 3| bar| 30|
# --- ------- ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514428.html
