Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 11

Loading and Inspecting Data in Pandas

This lesson is built with resources from medium.com and datacamp.com.

Hello! Welcome to the next lesson in our "Python Tools for AI and Data Manipulation" module.

In our last session, we explored the power of vectorization in NumPy, which is crucial for performing fast numerical computations. You learned how to apply operations to entire arrays at once, a technique that underpins the performance of virtually all AI and data science libraries in Python.

Now, we're going to move from raw numerical arrays to a more powerful and flexible tool designed specifically for data analysis: the Pandas library. This lesson will cover the learning outcome: Load datasets from common file formats into Pandas DataFrames and perform initial inspection.

Think of NumPy as providing the high-performance engine, and Pandas as providing the sophisticated chassis and dashboard for handling real-world, often messy, data. As a software engineer, you're used to working with structured data from databases or APIs. Pandas brings that same level of structure and utility to your data analysis workflow in Python.

1. From NumPy Arrays to Pandas DataFrames

While NumPy arrays are excellent for homogeneous numerical data, most real-world datasets are not so clean. You often have a mix of numbers, text, dates, and missing values, all organized in a tabular format like a spreadsheet or a database table.

This is where the Pandas DataFrame comes in. It is the core data structure in Pandas and has a few key characteristics:

  • It's a two-dimensional table with labeled axes (rows and columns).
  • Columns can have different data types (e.g., integer, float, string, datetime).
  • It's built on top of NumPy, so you still get great performance for numerical operations.

By convention, Pandas is imported with the alias pd:

import pandas as pd

2. Loading Data into a DataFrame

The first step in any data-centric project is to get your data into a workable format. Pandas excels at this, providing simple functions to read data from a wide variety of sources.

The following resource provides a great overview of the most common data loading functions. We will focus on CSV, Excel, and JSON, as these are formats you'll encounter frequently.

Python pandas Tutorial: The Ultimate Guide for Beginners

This section of the DataCamp tutorial, 'Python pandas Tutorial: The Ultimate Guide for Beginners', provides clear code examples for loading data from the most common file types.

Find the section titled 'Importing data in pandas'. Read the importing guide. Focus on the examples for CSV, Excel (single and multiple sheets), and JSON files. Notice the function naming pattern: read_<file_type>().

Let's summarize the key functions:

  • pd.read_csv('path/to/your/file.csv'): This is the workhorse function for reading comma-separated value files, arguably the most common format for sharing datasets.

  • pd.read_excel('path/to/your/file.xlsx', sheet_name='Sheet1'): For reading Microsoft Excel files. A very useful parameter is sheet_name, which lets you specify which sheet to load by name or by its index (e.g., sheet_name=0 for the first sheet).

  • pd.read_json('path/to/your/file.json'): For reading JSON files. JSON data can be structured in a few different ways. As a backend developer, you've likely seen JSON used in APIs. A common format for data logs is "JSON lines", where each line in a file is a separate JSON object. To read this, you use the lines=True argument.

This image illustrates how `pd.read_json()` can handle different JSON structures. The `lines=True` parameter is used when each line of the file is a complete JSON object, a common format in data streaming and logs.
  • pd.read_sql(query, connection_object): Pandas can also read directly from a SQL database. This requires a database connection object (from a library like sqlite3 or psycopg2) and a SQL query string. This can be very efficient for pulling data directly into your analysis environment.

3. Performing an Initial Inspection

Once you've loaded your data into a DataFrame, you should never assume it's perfect. The next critical step is to perform an initial inspection to understand its structure, content, and quality. This is like running a health check on your data.

The resource we used before also covers the fundamental methods for this initial exploration.

Python pandas Tutorial: The Ultimate Guide for Beginners

This part of the tutorial demonstrates the essential methods for getting a quick overview of your new DataFrame.

Find the section 'Viewing and understanding DataFrames using pandas'. Read the data inspection methods. Focus on the purpose of .head(), .tail(), .describe(), .info(), and .shape.

Here's a breakdown of the essential inspection toolkit:

  • .head(n=5) and .tail(n=5): These methods are the simplest first step. They show you the first or last n rows of your DataFrame, respectively. This helps you verify that the data loaded correctly and gives you a feel for the column names and data values.

    # Assuming 'df' is a DataFrame you've loaded
    # print(df.head()) 
    
  • .shape: This is an attribute (not a method, so no parentheses) that returns a tuple representing the dimensions of the DataFrame: (number_of_rows, number_of_columns). This is identical to the .shape attribute of a NumPy array.

    # num_rows, num_cols = df.shape
    # print(f"The dataset has {num_rows} rows and {num_cols} columns.")
    
  • .info(): This is one of the most useful methods for a quick summary. It provides:

    • The total number of rows (entries).
    • A list of all columns.
    • The count of non-null values for each column.
    • The data type (Dtype) of each column.
    • Memory usage.

    This is your primary tool for spotting missing data at a glance (if a column's non-null count is less than the total number of entries) and for checking if columns have been assigned the correct data type.

This diagram shows how the `.info()` method provides a concise summary of a DataFrame, including the column names, non-null counts, and data types (Dtypes), which is essential for initial data assessment.
  • .describe(): This method provides descriptive statistics for all numerical columns. It calculates the count, mean, standard deviation, minimum, maximum, and quartiles. This is incredibly useful for getting a sense of the distribution and scale of your numerical data and for spotting potential outliers (e.g., a max value that seems impossibly high). A useful trick is to add .T to transpose the output, which makes it easier to read if you have many columns.
    # print(df.describe().T)
    
Test your understanding!

Imagine you have been given a dataset in a file named customer_data.csv. You load it into a DataFrame called customers_df.

What single line of code would you use to get a quick summary that tells you if any of the columns have missing values and what data type each column is? After running it, you see that the total_spent column has a data type of object instead of a number. Which inspection method revealed this?

Show answer

The single line of code would be:

customers_df.info()

The .info() method provides both the non-null count for each column (revealing missing values) and the data type (Dtype) of each column. It would be .info() that shows total_spent as an object type, signaling a potential data quality issue that needs to be addressed.


Conclusion

In this lesson, you've taken the first and most fundamental step in working with Pandas. You now have a solid toolkit for getting data into a DataFrame and performing a crucial initial analysis.

Here are your key takeaways:

  • The Pandas DataFrame is a powerful, 2D data structure for holding heterogeneous data in a tabular format.
  • You can load data from various sources using the pd.read_<format>() family of functions, such as pd.read_csv() and pd.read_json().
  • Initial data inspection is a critical first step. The key methods are:
    • .head() and .tail() to preview rows.
    • .shape to see the dimensions.
    • .info() for a technical summary, including data types and null counts.
    • .describe() for statistical summaries of numerical columns.

Next up:
Real-world data is rarely perfect. The initial inspection you just learned how to do often reveals problems like missing values or incorrect data types. In the next lesson, we will tackle these issues head-on by learning how to perform basic data cleaning operations in Pandas.