scala - 读取具有不同列顺序的文件
问题描述
我有几个带有标题的 csv 文件,但我发现有些文件有不同的列顺序。有没有办法用 Spark 来处理这个问题,我可以为每个文件定义选择顺序,这样主 DF 就不会出现 col x 可能具有 col y 值的不匹配?
我目前的阅读 -
val masterDF = spark.read.option("header", "true").csv(allFiles:_*)
解决方案
Extract all file names
and store into list variable.
Then define
schema
of with all the columns in it.iterate
through each file using header true, so we are reading each file separately.unionA
ll the new dataframe with the existing dataframe.
Example:
file_lst=['<path1>','<path2>']
from pyspark.sql.functions import *
from pyspark.sql.types import *
#define schema for the required columns
schema = StructType([StructField("column1",StringType(),True),StructField("column2",StringType(),True)])
#create an empty dataframe
df=spark.createDataFrame([],schema)
for i in file_lst:
tmp_df=spark.read.option("header","true").csv(i).select("column1","column2")
df=df.unionAll(tmp_df)
#display results
df.show()
推荐阅读
- typescript - Vue js 3 - 类型“CreateComponentPublicInstance<{}、{}、{}、{}、{} 上不存在属性“项目”,
- python - 返回字符串无穷次
- asp.net-mvc - 如何创建本地 SQLite 数据库并一起发布到 IIS?(ASP.NET MVC)
- webview - 从浏览器运行我的 VodaPay 小程序 web-view 应用程序时,我无法访问我的图书馆
- php - 转换链接时TCPDF MultiCell ishtml错误,只有第一个可点击
- json - 颤振错误:列表
不是 Map 类型的子类型 - reactjs - 如何在 React js 中单击按钮时调用函数?
- angular - 在单元格值更改之前验证?
- azure - Azure VideoIndexer apikey 参数的名称是什么?
- python - 当我将真实值与它们的平均值进行比较时,r2_score() 获得非零值