我有 5 個 CSV 檔案,標題僅在第一個檔案中。我想使用 spark 讀取和創建資料幀。我下面的代碼有效,但是,我使用此方法丟失了 4 行資料,因為在最終讀取時標頭設定為 true。如果我將標題設定為 false,我會回傳 4 行資料,但我也會從第一個檔案中獲取實際標題作為資料中的一行。
有沒有更有效的方法來做到這一點,以便標題不會在我的資料集中顯示為一行?
header = spark.read \
.format("csv") \
.option("header", "true") \
.option("inferSchema", "true") \
.load("path/file-1")
schema = header.schema
df = spark.read \
.format("csv") \
.option("header", "true") \
.schema(schema) \
.load("path")
uj5u.com熱心網友回復:
不幸的是,我認為沒有一種簡單的方法可以滿足您的需求。有一個解決方法看起來像你所做的。您可以讀取第一個檔案以獲取架構,讀取除第一個檔案之外的所有檔案option("header", "false"),然后合并第一個檔案和其余檔案。
在python中,它看起來像這樣:
first_file = "path/file-1"
header = spark.read.option("header", "true") \
.option("inferSchema", "true").csv(first_file)
schema = header.schema
# I use binaryFiles simply to get the list of the files in the folder
# Not that the files are not read.
# Any other mean to list files in a directory would do the trick as well.
all_files = files = spark.sparkContext.binaryFiles("path")\
.map(lambda x : x[0]).collect()
all_files_but_first = [f for f in all_files if not f.endswith(first_file)]
df = spark.read.option("header", "false") \
.schema(schema).csv(all_files_but_first)\
.union(header)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334502.html
