Last Updated on July 19, 2023 by Editorial Team
Author(s): Vivek Chaudhary
Originally published on Towards AI.
The objective of this article is to process multiple delimited files using Apache spark with Python Programming language. This is a real-time scenario where an application can share multiple delimited file,s and the Dev Team has to process the same. We will learn how we can handle the challenge.
The input Data set is as below:
[email protected]@#Age <--Header
vivek, [email protected]@#30 <--row1
john, [email protected]@#28 <--row2
Approach1: Let’s try to read the file using read.csv() and see the output:
from pyspark.sql import SparkSessionfrom pyspark.sql import SparkSession
#Note: Output is not the desired one and so the processing will not yield the desired results
Approach2: Next, read the file using read.csv() with option() parameter and pass the delimiter as an argument having the value ‘@@#’ and see the output:
#Note: spark throws error when we try to pass delimiter of more than one character.
Approach3: Next way is to use read.text() method of spark.
#Note: spark.read.text returns a DataFrame.
Each line in a text file represents a record in DataFrame with just one column “value”. To convert into multiple columns, we will use map transformation and split method to transform and split the column values.
#first() returns the first record of dataset
[email protected]@#Age#split('delimiter') the string on basis of the delimiter
#define the schema of the Dataframe to be createdschema=header.split(‘@@#’)
The next step is to split the row and create separate columns:
#filter operation is removing the header
#map operation is splitting each record as per delimiter
#.rdd converts DF to rdd and toDF converts the rdd back to DFmult_df.filter(mult_df[‘value’]!=header).rdd.map(lambda x:x.split(‘@@#’)).toDF(schema).show()
Hurray!! We are able to split the data on the basis of multiple delimiter ‘@@#’.
· Read Multiple Delimited Dataset using spark.read.text() method
· use of map(), filter() transformations
Thanks to all for reading my blog, and If you like my content and explanation, please follow me on medium and share your feedback, which will always help all of us to enhance our knowledge.
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.
Published via Towards AI