Post Syndicated from Ismail Makhlouf original https://aws.amazon.com/blogs/big-data/clean-up-your-excel-and-csv-files-without-writing-code-using-aws-glue-databrew/
Managing data within an organization is complex. Handling data from outside the organization adds even more complexity. As the organization receives data from multiple external vendors, it often arrives in different formats, typically Excel or CSV files, with each vendor using their own unique data layout and structure. In this blog post, we’ll explore a solution that streamlines this process by leveraging the capabilities of AWS Glue DataBrew.
DataBrew is an excellent tool for data quality and preprocessing. You can use its built-in transformations, recipes, as well as integrations with the AWS Glue Data Catalog and Amazon Simple Storage Service (Amazon S3) to preprocess the data in your landing zone, clean it up, and send it downstream for analytical processing.
In this post, we demonstrate the following:
- Extracting non-transactional metadata from the top rows of a file and merging it with transactional data
- Combining multi-line rows into single-line rows
- Extracting unique identifiers from within strings or text
Solution overview
For this use case, imagine you’re a data analyst working at your organization. The sales leadership have requested a consolidated view of the net sales they are making from each of the organization’s suppliers. Unfortunately, this information is not available in a database. The sales data comes from each supplier in layouts like the following example.
However, with hundreds of resellers, manually extracting the information at the top is not feasible. Your goal is to clean up and flatten the data into the following output layout.
To achieve this, you can use pre-built transformations in DataBrew to quickly get the data in the layout you want.
Prerequisites
For this walkthrough, you should have the following prerequisites:
- An AWS account.
- An AWS Identity and Access Management (IAM) role with permissions for Amazon S3 and DataBrew. For more information, refer to Setting up AWS Identity and Access Management (IAM) permissions.
Connect to the dataset
The first thing we need to do is upload the input dataset to Amazon S3. Create an S3 bucket for the project and create a folder to upload the raw input data. The output data will be stored in another folder in a later step.
Next, we need to connect DataBrew to our CSV file. We create what we call a dataset, which
is an artifact that points to whatever data source we will be using. Navigate to “Datasets” on
the left hand menu.
Ensure the Column header values field is set to Add default header. The input CSV has an irregular format, so the first row will not have the needed column values.
Create a project
To create a new project, complete the following steps:
- On the DataBrew console, choose Projects in the navigation pane.
- Choose Create project.
- For Project name, enter
FoodMartSales-AllUpProject. - For Attached recipe, choose Create new recipe.
- For Recipe name, enter
FoodMartSales-AllUpProject-recipe.

- For Select a dataset, select My datasets.
- Select the
FoodMartSales-AllUpdataset.

- Under Permissions, for Role name, choose the IAM role you created as a prerequisite or create a new role.
- Choose Create project.

After the project is opened, an interactive session is created where you can author transformations on a sample of the data.
Extract non-transactional metadata from within the contents of the file and merge it with transactional data
In this section, we consider data that has metadata on the first few rows of the file, followed by transactional data. We walk through how to extract data relevant to the whole file from the top of the document and combine it with the transactional data into one flat table.
Extract metadata from the header and remove invalid rows
Complete the following steps to extract metadata from the header:
- Choose Conditions and then choose IF.

- For Matching conditions, choose Match all conditions.
- For Source, choose Value of and
Column_1. - For Logical condition, choose Is exactly.
- For Enter a value, choose Enter custom value and enter
RESELLER NAME. - For Flag result value as, choose Custom value.
- For Value if true, choose Select source column and set Value of to
Column_2. - For Value if false, choose Enter custom value and enter
INVALID. - Choose Apply.
Your dataset should now look like the following screenshot, with the Reseller Name value extracted to a column by itself.
Next, you remove invalid rows and fill the rows with the Reseller Name value.
- Choose Clean and then choose Custom values.

- For Source column, choose
ResellerName. - For Specify values to remove, choose Custom value.
- For Values to remove, choose Invalid.
- For Apply transform to, choose All rows.
- Choose Apply.
- Choose Missing and then choose Fill with most frequent value.

- For Source column, choose
FirstTransactionDate. - For Missing value action, choose Fill with most frequent value.
- For Apply transform to, choose All rows.
- Choose Apply.
Your dataset should now look like the following screenshot, with the Reseller Name value extracted to a column by itself.
Repeat the same steps in this section for the rest of the metadata, including Reseller Email Address, Reseller ID, and First Transaction Date.
Promote column headers and clean up data
To promote column headers, complete the following steps:
- Reorder the columns to put the metadata columns to the left of the dataset by choosing Column, Move column, and Start of the table.

- Rename the columns with the appropriate names.

Now you can clean up some columns and rows.
- Delete unnecessary columns, such as
Column_7.
You can also delete invalid rows by filtering out records that don’t have a transaction date value.
- Choose the ABC icon on the menu of the
Transaction_Datecolumn and choose date.

- For Handle invalid values, select Delete rows, then choose Apply.

The dataset should now have the metadata extracted and the column headers promoted.
Combine multi-line rows into single-line rows
The next issue to address is transactions pertaining to the same row that are split across multiple lines. In the following steps, we extract the needed data from the rows and merge it into single-line transactions. For this example specifically, the Reseller Margin data is split across two lines.

Complete the following steps to get the Reseller Margin value on the same line as the corresponding transaction. First, we identify the Reseller Margin rows and store them in a temporary column.
- Choose Conditions and then choose IF.

- For Matching conditions, choose Match all conditions.
- For Source, choose Value of and
Transaction_ID. - For Logical condition, choose Contains.
- For Enter a value, choose Enter custom value and enter Reseller Margin.
- For Flag result value as, choose Custom value.
- For Value if true, choose Select source column set Value of to
TransactionAmount. - For Value if false, choose Enter custom value and enter Invalid.
- For Destination column, choose
ResellerMargin_Temp. - Choose Apply.
Next, you shift the Reseller Margin value up one row.
- Choose Functions and then choose NEXT.

- For Source column, choose
ResellerMargin_Temp. - For Number of rows, enter
1. - For Destination column, choose
ResellerMargin. - For Apply transform to, choose All rows.
- Choose Apply.
Next, delete the invalid rows.
- Choose Missing and then choose Remove missing rows.

- For Source column, choose
TransactionDate. - For Missing value action, choose Delete rows with missing values.
- For Apply transform to, choose All rows.
- Choose Apply.
Your dataset should now look like the following screenshot, with the Reseller Margin value extracted to a column by itself.
With the data structured properly, we can move on to mining the cleaned data.
Extract unique identifiers from within strings and text
Many types of data contain important information stored as unstructured text in a cell. In this section, we look at how to extract this data. Within the sample dataset, the BankTransferText column has valuable information around our resellers’ registered bank account numbers as well as the currency of the transaction, namely IBAN, SWIFT Code, and Currency.
Complete the following steps to extract IBAN, SWIFT code, and Currency into separate columns. First, you extract the IBAN number from the text using a regular expression (regex).
- Choose Extract and then choose Custom value or pattern.

- For Create column options, choose Extract values.
- For Source column, choose
BankTransferText. - For Extract options, choose Custom value or pattern.
- For Values to extract, enter
[a-zA-Z][a-zA-Z][0-9]{2}[A-Z0-9]{1,30}. - For Destination column, choose IBAN.
- For Apply transform to, choose All rows.
- Choose Apply.
- Extract the SWIFT code from the text using a regex following the same steps used to extract the IBAN number, but using the following regex instead:
(?!^)(SWIFT Code: )([A-Z]{2}[A-Z0-9]+).
Next, remove the SWIFT Code: label from the extracted text.
- Choose Remove and then choose Custom values.

- For Source column, choose
SWIFT Code. - For Specify values to remove, choose Custom value.
- For Apply transform to, choose All rows.
- Extract the currency from the text using a regex following the same steps used to extract the IBAN number, but using the following regex instead:
(?!^)(Currency: )([A-Z]{3}). - Remove the
Currency:label from the extracted text following the same steps used to remove theSWIFT Code:label.
You can clean up by deleting any unnecessary columns.
- Choose Column and then choose Delete.

- For Source columns, choose
BankTransferText. - Choose Apply.
- Repeat for any remaining columns.
Your dataset should now look like the following screenshot, with IBAN, SWIFT Code, and Currency extracted to separate columns.
Write the transformed data to Amazon S3
With all the steps captured in the recipe, the last step is to write the transformed data to Amazon S3.
- For Job name, enter
FoodMartSalesToDataLake.

- For Output to, choose Amazon S3.
- For File type, choose CSV.
- For Delimiter, choose Comma (,).
- For Compression, choose None.
- For S3 bucket owners’ account, select Current AWS account.
- For S3 location, enter
s3://{name of S3 bucket}/clean/. - For Role name, choose the IAM role created as a prerequisite or create a new role.
- Choose Create and run job.

- Go to the Jobs tab and wait for the job to complete.
- Navigate to the job output folder on the Amazon S3 console.
- Download the CSV file and view the transformed output.
Your dataset should look similar to the following screenshot.
Clean up
To optimize cost, make sure to clean up the resources deployed for this project by completing the following steps:
- Delete every DataBrew project along with their linked recipes.
- Delete all the DataBrew datasets.
- Delete the contents in your S3 bucket.
- Delete the S3 bucket.
Conclusion
The reality of exchanging data with suppliers is that we can’t always control the shape of the input data. With DataBrew, we can use a list of pre-built transformations and repeatable steps to transform incoming data into a desired layout and extract relevant data and insights from Excel or CSV files. Start using DataBrew today and transform 3 rd party files into structured datasets ready for consumption by your business.
About the Author
Ismail Makhlouf is a Senior Specialist Solutions Architect for Data Analytics at AWS. Ismail focuses on architecting solutions for organizations across their end-to-end data analytics estate, including batch and real-time streaming, big data, data warehousing, and data lake workloads. He primarily works with direct-to-consumer platform companies in the ecommerce, FinTech, PropTech, and HealthTech space to achieve their business objectives with well-architected data platforms.








































Roy (KDS) Wang is a Senior Product Manager with Amazon Kinesis Data Streams. He is passionate about learning from and collaborating with customers to help organizations run faster and smarter. Outside of work, Roy strives to be a good dad to his new son and builds plastic model kits.
Ali Alemi is a Streaming Specialist Solutions Architect at AWS. Ali advises AWS customers with architectural best practices and helps them design real-time analytics data systems that are reliable, secure, efficient, and cost-effective. He works backward from customer’s use cases and designs data solutions to solve their business problems. Prior to joining AWS, Ali supported several public sector customers and AWS consulting partners in their application modernization journey and migration to the Cloud.
Imtiaz (Taz) Sayed is the WW Tech Leader for Analytics at AWS. He enjoys engaging with the community on all things data and analytics. He can be reached via
Navnit Shukla serves as an AWS Specialist Solution Architect with a focus on Analytics. He possesses a strong enthusiasm for assisting clients in discovering valuable insights from their data. Through his expertise, he constructs innovative solutions that empower businesses to arrive at informed, data-driven choices. Notably, Navnit Shukla is the accomplished author of the book titled “Data Wrangling on AWS.” He can be reached via 



Prantik Gachhayat is an Enterprise Architect at Infosys having experience in various technology fields and business domains. He has a proven track record helping large enterprises modernize digital platforms and delivering complex transformation programs. Prantik specializes in architecting modern data and analytics platforms in AWS. Prantik loves exploring new tech trends and enjoys cooking.
Ashutosh Dubey is a Senior Partner Solutions Architect and Global Tech leader at Amazon Web Services based out of New Jersey, USA. He has extensive experience specializing in the Data and Analytics and AIML field including generative AI, contributed to the community by writing various tech contents, and has helped Fortune 500 companies in their cloud journey to AWS.




















Michael Hamilton is a Sr Analytics Solutions Architect focusing on helping enterprise customers in the south east modernize and simplify their analytics workloads on AWS. He enjoys mountain biking and spending time with his wife and three children when not working.
Cody Penta is a Solutions Architect at Amazon Web Services and is based out of Charlotte, NC. He has a focus in security and CDK, and enjoys solving the really difficult problems in the technology world. Off the clock, he loves relaxing in the mountains, coding personal projects, and gaming.
Angus Ferguson is a Solutions Architect at AWS who is passionate about meeting customers across the world, helping them solve their technical challenges. Angus specializes in Data & Analytics with a focus on customers in the financial services industry.
Mukul Sharma is a Software Development Engineer on Data & Analytics (DnA) organization at GoDaddy. He is a polyglot programmer with experience in a wide array of technologies to rapidly deliver scalable solutions. He enjoys singing karaoke, playing various board games, and working on personal programming projects in his spare time.
Ozcan Ilikhan is a Director of Engineering on Data & Analytics (DnA) organization at GoDaddy. He is passionate about solving customer problems and increasing efficiency using data and ML/AI. In his spare time, he loves reading, hiking, gardening, and working on DIY projects.
Harsh Vardhan Singh Gaur is an AWS Solutions Architect, specializing in analytics. He has over 6 years of experience working in the field of big data and data science. He is passionate about helping customers adopt best practices and discover insights from their data.
Ramesh Kumar Venkatraman is a Senior Solutions Architect at AWS who is passionate about containers and databases. He works with AWS customers to design, deploy, and manage their AWS workloads and architectures. In his spare time, he loves to play with his two kids and follows cricket.







Phil Bates is a Senior Analytics Specialist Solutions Architect at AWS. He has more than 25 years of experience implementing large-scale data warehouse solutions. He is passionate about helping customers through their cloud journey and using the power of ML within their data warehouse.
























John Cherian is Senior Solutions Architect(SA) at Amazon Web Services helps customers with strategy and architecture for building solutions on AWS.
Emerson Antony is Senior Cloud Architect at Amazon Web Services helps customers with implementing AWS solutions.
Kiran Anand is Principal AWS Data Lab Architect at Amazon Web Services helps customers with Big data & Analytics architecture.














Kartikay Khator is a Solutions Architect in Global Life Sciences at Amazon Web Services (AWS). He is passionate about building innovative and scalable solutions to meet the needs of customers, focusing on AWS Analytics services. Beyond the tech world, he is an avid runner and enjoys hiking.
Kamen Sharlandjiev is a Sr. Big Data and ETL Solutions Architect and Amazon AppFlow expert. He’s on a mission to make life easier for customers who are facing complex data integration challenges. His secret weapon? Fully managed, low-code AWS services that can get the job done with minimal effort and no coding.
Anshul Sharma is a Software Development Engineer in AWS Glue Team. He is driving the connectivity charter which provide Glue customer native way of connecting any Data source (Data-warehouse, Data-lakes, NoSQL etc) to Glue ETL Jobs. Beyond the tech world, he is a cricket and soccer lover.




Stefan Gromoll is a Senior Performance Engineer with Amazon Redshift team where he is responsible for measuring and improving Redshift performance. In his spare time, he enjoys cooking, playing with his three boys, and chopping firewood.
Aamer Shah is a Senior Engineer in the Amazon Redshift Service team.
Sanket Hase is a Software Development Manager in the Amazon Redshift Service team.
Orestis Polychroniou is a Principal Engineer in the Amazon Redshift Service team.

Prashant Agrawal is a Sr. Search Specialist Solutions Architect with Amazon OpenSearch Service. He works closely with customers to help them migrate their workloads to the cloud and helps existing customers fine-tune their clusters to achieve better performance and save on cost. Before joining AWS, he helped various customers use OpenSearch and Elasticsearch for their search and log analytics use cases. When not working, you can find him traveling and exploring new places. In short, he likes doing Eat → Travel → Repeat.



Mikhail Vaynshteyn is a Solutions Architect with Amazon Web Services. Mikhail works with healthcare and life sciences customers to build solutions that help improve patients’ outcomes. Mikhail specializes in data analytics services.
Muthu Pitchaimani is a Search Specialist with Amazon OpenSearch Service. He builds large-scale search applications and solutions. Muthu is interested in the topics of networking and security, and is based out of Austin, Texas.



Sakti Mishra is a Principal Solutions Architect at AWS, where he helps customers modernize their data architecture and define their end-to-end data strategy, including data security, accessibility, governance, and more. He is also the author of the book
Bhavana Chirumamilla is a Senior Resident Architect at AWS with a strong passion for data and machine learning operations. She brings a wealth of experience and enthusiasm to help enterprises build effective data and ML strategies. In her spare time, Bhavana enjoys spending time with her family and engaging in various activities such as traveling, hiking, gardening, and watching documentaries.
Sheela Sonone is a Senior Resident Architect at AWS. She helps AWS customers make informed choices and trade-offs about accelerating their data, analytics, and AI/ML workloads and implementations. In her spare time, she enjoys spending time with her family—usually on tennis courts.
Daniel Bruno is a Principal Resident Architect at AWS. He had been building analytics and machine learning solutions for over 20 years and splits his time helping customers build data science programs and designing impactful ML products.





























Aish Gunasekar is a Specialist Solutions Architect with a focus on Amazon OpenSearch Service. Her passion at AWS is to help customers design highly scalable architectures and help them in their cloud adoption journey. Outside of work, she enjoys hiking and baking.
Satish Nandi is a Senior Technical Product Manager for Amazon OpenSearch Service.
Jon Handler is a Senior Principal Solutions Architect at Amazon Web Services based in Palo Alto, CA. Jon works closely with OpenSearch and Amazon OpenSearch Service, providing help and guidance to a broad range of customers who have search and log analytics workloads that they want to move to the AWS Cloud. Prior to joining AWS, Jon’s career as a software developer included 4 years of coding a large-scale, ecommerce search engine. Jon holds a Bachelor of the Arts from the University of Pennsylvania, and a Master of Science and a PhD in Computer Science and Artificial Intelligence from Northwestern University.