使用pyspark读取多个csv文件

使用pyspark读取多个csv文件,pyspark,Pyspark,我需要一次读取多个csv文件。现在,这些csv文件可能具有可变的列数和任意顺序。我们要求从csv文件中只读取特定列。我们怎么做?我曾尝试定义自定义模式,但后来我在列中得到了不同的数据 例如: CSV文件 身份证、姓名、地址 如何仅选择Id和地址列。因为若我说select(Id,Address),那个么它会在Address列中给我Id和Name数据。在读取时,我只想根据标题名称选择ID和地址列 谢谢, Naveed您可以迭代文件并创建最终数据帧,如: files = ['path/to/file1

我需要一次读取多个csv文件。现在,这些csv文件可能具有可变的列数和任意顺序。我们要求从csv文件中只读取特定列。我们怎么做?我曾尝试定义自定义模式,但后来我在列中得到了不同的数据

例如:

CSV文件

身份证、姓名、地址 如何仅选择Id和地址列。因为若我说select(Id,Address),那个么它会在Address列中给我Id和Name数据。在读取时,我只想根据标题名称选择ID和地址列

谢谢,
Naveed

您可以迭代文件并创建最终数据帧,如:

files = ['path/to/file1.csv', 'path/to/file2.csv', 'path/to/file3.csv', 'path/to/file4.csv']

#define the output dataframe's schema column name and type should be correct
schema = t.StructType([
    t.StructField("a", t.StringType(), True), StructField("c", t.StringType(), True)
])

output_df = spark.createDataFrame([],schema)



for i,file in enumerate(data):
    df = spark.read.csv(file, header=True)
    output_df = output_df.union(df.select('a','c'))

output_df.show()

output_df将包含所需的输出。

您可以迭代文件并创建最终数据帧,如:

files = ['path/to/file1.csv', 'path/to/file2.csv', 'path/to/file3.csv', 'path/to/file4.csv']

#define the output dataframe's schema column name and type should be correct
schema = t.StructType([
    t.StructField("a", t.StringType(), True), StructField("c", t.StringType(), True)
])

output_df = spark.createDataFrame([],schema)



for i,file in enumerate(data):
    df = spark.read.csv(file, header=True)
    output_df = output_df.union(df.select('a','c'))

output_df.show()

输出\ u df将包含您所需的输出。

我们正在解析文件,读取CSV时header=True…尝试然后共享resultNice解决方案。。!是否有任何方法可以从csv本身读取所需的列数,而不是遍历文件。由于我们有大约10000个文件,对它们进行迭代将导致非常糟糕的结果performance@ShubhamJain,如何以您提到的列表格式获取datalake目录中所有文件的列表。从10000个文件中迭代读取数据时,性能非常差。我们需要找到只从CSV中读取所选列的方法。在读取CSV时,我们正在以header=True的方式解析文件…尝试然后共享resultNice解决方案。。!是否有任何方法可以从csv本身读取所需的列数,而不是遍历文件。由于我们有大约10000个文件,对它们进行迭代将导致非常糟糕的结果performance@ShubhamJain,如何以您提到的列表格式获取datalake目录中所有文件的列表。从10000个文件中迭代读取数据时,性能非常差。我们需要找到只从csv中读取选定列的方法