Python Tutorial: Handling errors and missing data

DataCamp · Beginner ·🛠️ AI Tools & Apps ·6y ago

Key Takeaways

This video tutorial demonstrates how to handle errors and missing data when importing flat files using Python's pandas library, specifically using the read_csv function with parameters such as dtype, na_values, error_bad_lines, and warn_bad_lines.

Full Transcript

so far we've imported flat files with minor tweaks to set column names and manage the amount of data loaded this is enough if the data is already in great shape but what if there are issues with the data or the import common issues include incorrect column data types which can hinder analysis missing values indicated with custom designators or records that pandas cannot read luckily read CSV offers ways to address these issues during import reducing the wrangling needed later on when importing data pandas infers each columns data type sometimes a guess is wrong checking the data types in the tax data we see that pandas interpreted zip codes as integers they're more accurately modeled as strings though zip codes are not quantities and include meaningful leading zeros instead of letting pandas guess we can set the data type of any or all columns with read CSV SD type keyword argument D type takes a dictionary where each key is a column name and each value is the data type that column should be note that non-standard data types like pandas categories must be passed in quotations here we specify that the zip code column should contain strings leaving pandas to infer the other columns printing the new data frames D types we see that zip codes D type is object which is the pandas counterpart to Python strings missing data is another common issue pandas automatically recognizes some values like n/a or null as missing data enabling the use of handy data cleaning functions but sometimes missing values are represented in ways that pandas won't catch such as with dummy codes in the tax data records were sorted so that the first few have the zip code zero which is not a valid code and should be treated as missing we can tell pandas to consider these missing data with the n/a values keyword argument na values accepts either a single value a list of values or a dictionary of columns and values in that column to treat as missing let's pass a dictionary specifying that any zeros in zip code should be treated as missing data then we filter the data using the is n/a method on the zip code column to view rows with missing postal codes one last issue you may face are lines that pandas just can't parse for example a record could have more values than there are columns like the second record in this corrupted version of the tax data let's try reading it by default trying to load this file results in the long error and no data is imported luckily we can change this behavior with two arguments error bad lines and warned bad lines both take boolean or true false values setting error bad lines to false makes pandas skip bad lines and load the rest of the data instead of throwing an error warned bad lines tells pandas whether to display messages when unpossible lines are skipped let's try importing the corrupted file again this time with error bad lines set to false and warn bad lines equal to true success a word of caution if lines were skipped it's worth investigating what was left out to see if there are underlying issues that should be addressed in this video you've learned about common issues encountered importing data from flat files and how to handle those issues now it's your turn to practice

Original Description

Want to learn more? Take the full course at https://learn.datacamp.com/courses/streamlined-data-ingestion-with-pandas at your own pace. More than a video, you'll learn hands-on coding & quickly apply skills to your daily work. --- So far, we've imported flat files with minor tweaks to set column names and manage the amount of data loaded. This is enough if the data is already in great shape. But what if there are issues with the data or the import? Common issues include incorrect column data types, which can hinder analysis, missing values indicated with custom designators, or records that pandas cannot read. Luckily, read CSV offers ways to address these issues during import, reducing the wrangling needed later on. When importing data, pandas infers each column's data type. Sometimes, it guesses wrong. Checking data types in the tax data, we see that pandas interpreted ZIP codes as integers. They're more accurately modeled as strings, though -- ZIP codes are not quantities and include meaningful leading zeros. Instead of letting pandas guess, we can set the data type of any or all columns with read CSV's dtype keyword argument. Dtype takes a dictionary, where each key is a column name and each value is the data type that column should be. Note that non-standard data types, like pandas categories, must be passed in quotations. Here, we specify that the zipcode column should contain strings, leaving pandas to infer the other columns. Printing the new data frame's dtypes, we see that zipcode's dtype is "object", which is the pandas counterpart to Python strings. Missing data is another common issue. pandas automatically recognizes some values, like “N/A” or “null”, as missing data, enabling the use of handy data-cleaning functions. But sometimes missing values are represented in ways that pandas won't catch, such as with dummy codes. In the tax data, records were sorted so that the first few have the ZIP code 0, which is not a valid code and should be
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from DataCamp · DataCamp · 0 of 60

← Previous Next →
1 SQL Server Tutorial: Date manipulation
SQL Server Tutorial: Date manipulation
DataCamp
2 R Tutorial: Intermediate Interactive Data Visualization with plotly in R
R Tutorial: Intermediate Interactive Data Visualization with plotly in R
DataCamp
3 R Tutorial: Adding aesthetics to represent a variable
R Tutorial: Adding aesthetics to represent a variable
DataCamp
4 R Tutorial: Moving Beyond Simple Interactivity
R Tutorial: Moving Beyond Simple Interactivity
DataCamp
5 Python Tutorial: Why use ML for marketing? Strategies and use cases
Python Tutorial: Why use ML for marketing? Strategies and use cases
DataCamp
6 Python Tutorial: Preparation for modeling
Python Tutorial: Preparation for modeling
DataCamp
7 Python Tutorial: Machine Learning modeling steps
Python Tutorial: Machine Learning modeling steps
DataCamp
8 R Tutorial: The prior model
R Tutorial: The prior model
DataCamp
9 R Tutorial: Data & the likelihood
R Tutorial: Data & the likelihood
DataCamp
10 R Tutorial: The posterior model
R Tutorial: The posterior model
DataCamp
11 R Tutorial: An Introduction to plotly
R Tutorial: An Introduction to plotly
DataCamp
12 R Tutorial: Plotting a single variable
R Tutorial: Plotting a single variable
DataCamp
13 R Tutorial: Bivariate graphics
R Tutorial: Bivariate graphics
DataCamp
14 Python Tutorial: Customer Segmentation in Python
Python Tutorial: Customer Segmentation in Python
DataCamp
15 Python Tutorial: Time cohorts
Python Tutorial: Time cohorts
DataCamp
16 Python Tutorial: Calculate cohort metrics
Python Tutorial: Calculate cohort metrics
DataCamp
17 Python Tutorial: Cohort analysis visualization
Python Tutorial: Cohort analysis visualization
DataCamp
18 R Tutorial: Building Dashboards with flexdashboard
R Tutorial: Building Dashboards with flexdashboard
DataCamp
19 R Tutorial: Anatomy of a flexdashboard
R Tutorial: Anatomy of a flexdashboard
DataCamp
20 R Tutorial: Layout basics
R Tutorial: Layout basics
DataCamp
21 R Tutorial: Advanced layouts
R Tutorial: Advanced layouts
DataCamp
22 Python Tutorial: Time Series Analysis in Python
Python Tutorial: Time Series Analysis in Python
DataCamp
23 Python Tutorial: Correlation of Two Time Series
Python Tutorial: Correlation of Two Time Series
DataCamp
24 Python Tutorial: Simple Linear Regressions
Python Tutorial: Simple Linear Regressions
DataCamp
25 Python Tutorial: Autocorrelation
Python Tutorial: Autocorrelation
DataCamp
26 R Tutorial: The gapminder dataset
R Tutorial: The gapminder dataset
DataCamp
27 R Tutorial: The filter verb
R Tutorial: The filter verb
DataCamp
28 R Tutorial: The arrange verb
R Tutorial: The arrange verb
DataCamp
29 R Tutorial: The mutate verb
R Tutorial: The mutate verb
DataCamp
30 R Tutorial: What is cluster analysis?
R Tutorial: What is cluster analysis?
DataCamp
31 R Tutorial: Distance between two observations
R Tutorial: Distance between two observations
DataCamp
32 R Tutorial: The importance of scale
R Tutorial: The importance of scale
DataCamp
33 R Tutorial: Measuring distance for categorical data
R Tutorial: Measuring distance for categorical data
DataCamp
34 Python Tutorial: Plotting multiple graphs
Python Tutorial: Plotting multiple graphs
DataCamp
35 Python Tutorial: Customizing axes
Python Tutorial: Customizing axes
DataCamp
36 Python Tutorial: Legends, annotations, & styles
Python Tutorial: Legends, annotations, & styles
DataCamp
37 Python Tutorial: Introduction to iterators
Python Tutorial: Introduction to iterators
DataCamp
38 Python Tutorial: Playing with iterators
Python Tutorial: Playing with iterators
DataCamp
39 Python Tutorial: Using iterators to load large files into memory
Python Tutorial: Using iterators to load large files into memory
DataCamp
40 SQL Tutorial: Introduction to Relational Databases in SQL
SQL Tutorial: Introduction to Relational Databases in SQL
DataCamp
41 SQL Tutorial: Tables: At the core of every database
SQL Tutorial: Tables: At the core of every database
DataCamp
42 SQL Tutorial: Update your database as the structure changes
SQL Tutorial: Update your database as the structure changes
DataCamp
43 Python Tutorial: Classification-Tree Learning
Python Tutorial: Classification-Tree Learning
DataCamp
44 Python Tutorial: Decision-Tree for Classification
Python Tutorial: Decision-Tree for Classification
DataCamp
45 Python Tutorial: Decision-Tree for Regression
Python Tutorial: Decision-Tree for Regression
DataCamp
46 Python Tutorial: Census Subject Tables
Python Tutorial: Census Subject Tables
DataCamp
47 Python Tutorial: Census Geography
Python Tutorial: Census Geography
DataCamp
48 Python Tutorial: Using the Census API
Python Tutorial: Using the Census API
DataCamp
49 R Tutorial: A/B Testing in R
R Tutorial: A/B Testing in R
DataCamp
50 R Tutorial: Baseline Conversion Rates
R Tutorial: Baseline Conversion Rates
DataCamp
51 R Tutorial: Designing an Experiment - Power Analysis
R Tutorial: Designing an Experiment - Power Analysis
DataCamp
52 R Tutorial: Introduction to qualitative data
R Tutorial: Introduction to qualitative data
DataCamp
53 R Tutorial: Understanding your qualitative variables
R Tutorial: Understanding your qualitative variables
DataCamp
54 R Tutorial: Making Better Plots
R Tutorial: Making Better Plots
DataCamp
55 SQL Tutorial: OLTP and OLAP
SQL Tutorial: OLTP and OLAP
DataCamp
56 SQL Tutorial: Storing data
SQL Tutorial: Storing data
DataCamp
57 SQL Tutorial: Database design
SQL Tutorial: Database design
DataCamp
58 Python Tutorial: Introduction to spaCy
Python Tutorial: Introduction to spaCy
DataCamp
59 Python Tutorial: Statistical Models
Python Tutorial: Statistical Models
DataCamp
60 Python Tutorial: Rule-based Matching
Python Tutorial: Rule-based Matching
DataCamp

This video tutorial teaches how to handle common issues encountered when importing data from flat files using pandas, including incorrect column data types, missing values, and unparseable lines. By using the read_csv function with various parameters, users can reduce data wrangling needed later on and ensure accurate data analysis.

Key Takeaways
  1. Import a flat file using pandas' read_csv function
  2. Check the data types of each column and adjust as needed using the dtype parameter
  3. Identify and handle missing values using the na_values parameter
  4. Handle unparseable lines using the error_bad_lines and warn_bad_lines parameters
  5. Investigate skipped lines to address underlying issues
💡 Using the dtype and na_values parameters can help reduce data wrangling and ensure accurate data analysis, while the error_bad_lines and warn_bad_lines parameters can help handle unparseable lines and prevent errors.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →