Learn Pandas ยท 3/14

Exploring Your Data: The First Glance

9 min read

Course: Pandas ๐Ÿผ

Topic: Exploring Your Data: The First Glance

Hey there, data adventurer! So, you've just been handed a brand new dataset. It's like being given a treasure chest without a key. ๐Ÿ—๏ธ What's inside? Is it full of gold, or just a bunch of old socks? Before you can start building magnificent machine learning models or dazzling dashboards, you need to peek inside and understand what you're working with. This initial exploration is one of the most crucial steps in any data analysis project.

Think of yourself as a detective arriving at a new crime scene. You wouldn't just start accusing people randomly, would you? (Hopefully not! ๐Ÿ˜…) You'd first survey the area, check for clues, and get a general sense of what happened. That's exactly what we're going to do with our data.

In this guide, we'll cover the essential Pandas functions that help you take that critical first look at your data. Let's get started!


1. Quick Looks: head(), tail(), and sample()

The Problem: You have a dataset, maybe with thousands or even millions of rows. You can't possibly look at every single row at once. You need a quick and easy way to see a small part of the data to get a feel for the columns and the types of values they contain.

The Solution: Pandas provides three wonderfully simple functions to take a quick peek at your data: head(), tail(), and sample().

Imagine you've just received a massive, 1,000-page book. You probably wouldn't start by reading it from cover to cover. You might read the first few pages to see how the story begins (head()), flip to the last few pages to see how it ends (tail()), or open it to a random page in the middle to get a taste of the writing style (sample()).

head(): Peeking at the Top ๐Ÿ‘€

The .head() method shows you the first few rows of your DataFrame. By default, it displays the first 5 rows.

python
import pandas as pd

# Let's create a sample DataFrame of superheroes
data = {'name': ['Captain America', 'Iron Man', 'Black Widow', 'Thor', 'Hulk', 'Spider-Man', 'Doctor Strange'],
        'alias': ['Steve Rogers', 'Tony Stark', 'Natasha Romanoff', 'Thor Odinson', 'Bruce Banner', 'Peter Parker', 'Stephen Strange'],
        'power_level': [95, 98, 92, 97, 99, 94, 96]}
df = pd.DataFrame(data)

# Show the first 5 rows (default)
print(df.head())

Output:

apache
            name             alias  power_level
0  Captain America      Steve Rogers           95
1         Iron Man        Tony Stark           98
2      Black Widow  Natasha Romanoff           92
3             Thor      Thor Odinson           97
4             Hulk      Bruce Banner           99

You can also specify the number of rows you want to see by passing an integer to the function.

python
# Show the first 3 rows
print(df.head(3))

Output:

apache
            name             alias  power_level
0  Captain America      Steve Rogers           95
1         Iron Man        Tony Stark           98
2      Black Widow  Natasha Romanoff           92

tail(): Checking the End ๐Ÿ”š

Similarly, .tail() shows you the last few rows of your DataFrame. This is useful for checking if the data at the end has any issues or to see the most recent entries in time-series data.

python
# Show the last 5 rows (default)
print(df.tail())

Output:

apache
             name            alias  power_level
2      Black Widow  Natasha Romanoff           92
3             Thor      Thor Odinson           97
4             Hulk      Bruce Banner           99
5       Spider-Man      Peter Parker           94
6   Doctor Strange   Stephen Strange           96

And just like head(), you can specify the number of rows.

python
# Show the last 2 rows
print(df.tail(2))

Output:

apache
             name            alias  power_level
5       Spider-Man     Peter Parker           94
6   Doctor Strange  Stephen Strange           96

sample(): A Random Glimpse ๐ŸŽฒ

Sometimes, looking at the beginning or end isn't enough. The data might be sorted in a particular way. .sample() allows you to pull out one or more random rows from your DataFrame. This can give you a more unbiased view of your data.

python
# Get one random row
print(df.sample())

(Your output might be different because it's random!)
Output:

delphi
     name       alias  power_level
1  Iron Man  Tony Stark           98

You can also grab a specific number of random rows.

python
# Get 3 random rows
print(df.sample(3))

(Your output will vary!)
Output:

apache
             name            alias  power_level
6   Doctor Strange  Stephen Strange           96
0  Captain America     Steve Rogers           95
3             Thor     Thor Odinson           97

Fun Fact: The term "head" for the beginning of a file comes from early Unix commands. The head command was used to display the first part of a text file, and the name just stuck!


2. Understanding Structure: shape, columns, and index

The Problem: Now that you've seen some of the data, you need to understand its overall structure. How big is it? What are the "headers" or column names? How are the rows labeled?

The Solution: Pandas has attributes (not functions, so no parentheses () needed!) that give you this information in a flash: shape, columns, and index.

Let's go back to our library analogy. You have a new shipment of books (your DataFrame). shape tells you how many rows of shelves you have and how many books are on each shelf. columns gives you the genre of each book in a specific position (e.g., "Fiction," "History," "Science"). index is like the unique library card catalog number for each shelf.

shape: The Dimensions ๐Ÿ“

The .shape attribute returns a tuple containing the number of rows and columns in your DataFrame. It's a quick way to understand the size of your dataset.

python
# Get the shape of our superhero DataFrame
print(df.shape)

Output:

clojure
(7, 3)

This tells us our DataFrame has 7 rows and 3 columns. Simple as that!

columns: The Column Names ๐Ÿท๏ธ

The .columns attribute gives you a list of all the column names. This is incredibly useful for seeing what features you have to work with.

python
# Get the column names
print(df.columns)

Output:

stylus
Index(['name', 'alias', 'power_level'], dtype='object')

Industry Practice: You'll often find yourself copying this list of column names to use elsewhere in your code, so you don't have to type them all out and risk a typo!

index: The Row Labels #๏ธโƒฃ

The .index attribute describes the labels of the rows. By default, Pandas assigns a numerical index starting from 0.

python
# Get the index
print(df.index)

Output:

routeros
RangeIndex(start=0, stop=7, step=1)

This output tells us the index is a range of numbers starting at 0, stopping before 7, and stepping by 1 (i.e., 0, 1, 2, 3, 4, 5, 6).


3. Summary Statistics: Using info() and describe()

The Problem: You know the size and the column names, but what about the data types? Are the numbers actually numbers, or are they stored as text? Are there any missing values? What's the average, min, and max of the numerical columns?

The Solution: info() and describe() are two of the most powerful and commonly used methods for getting a high-level summary of your data.

info(): The Technical Summary ๐Ÿ“

The .info() method provides a concise summary of your DataFrame. This includes the index dtype and columns, the number of non-null values for each column, and memory usage.

python
# Get a summary of the DataFrame
print(df.info())

Output:

pgsql
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7 entries, 0 to 6
Data columns (total 3 columns):
 #   Column       Non-Null Count  Dtype
---  ------       --------------  -----
 0   name         7 non-null      object
 1   alias        7 non-null      object
 2   power_level  7 non-null      int64
dtypes: int64(1), object(2)
memory usage: 296.0+ bytes
None

Breaking it down:

  • RangeIndex: We have 7 entries, from index 0 to 6.
  • Data columns: We have 3 columns in total.
  • Non-Null Count: All columns have 7 non-null values. This is a crucial first step in checking for missing data!
  • Dtype: This tells us the data type of each column. object usually means string, and int64 is an integer.

describe(): The Statistical Summary ๐Ÿ“Š

The .describe() method gives you a statistical summary of the numerical columns in your DataFrame.

python
# Get a statistical summary
print(df.describe())

Output:

apache
       power_level
count     7.000000
mean     95.857143
std       2.410303
min      92.000000
25%      94.500000
50%      96.000000
75%      97.500000
max      99.000000

This gives you:

  • count: The number of non-null values.
  • mean: The average.
  • std: The standard deviation (a measure of how spread out the numbers are).
  • min: The minimum value.
  • 25%, 50%, 75%: The percentiles. The 50th percentile is the same as the median.
  • max: The maximum value.

Heads up! describe() is a data scientist's best friend. It can instantly tell you if there are strange outliers (e.g., a max value that's way too high) or if the data is distributed in an expected way.


4. Counting and Uniqueness: value_counts() and unique()

The Problem: You've got the general stats, but now you want to dig into specific columns, especially the categorical ones (the ones with text or distinct categories). How many times does each category appear? What are all the possible categories?

The Solution: value_counts() and unique() are your go-to tools for this.

Let's add a new column to our DataFrame for this section.

python
# Add a 'team' column
df['team'] = ['Avengers', 'Avengers', 'Avengers', 'Avengers', 'Avengers', 'Other', 'Other']

value_counts(): Counting a Column's Values ๐Ÿงฎ

The .value_counts() method returns a Series containing counts of unique values in a column. It's perfect for understanding the distribution of a categorical variable.

python
# Count the number of heroes in each team
print(df['team'].value_counts())

Output:

fortran
team
Avengers    5
Other       2
Name: count, dtype: int64

This immediately tells us that there are 5 heroes on the 'Avengers' team and 2 in the 'Other' category.

unique(): Finding the Unique Values โœจ

If you just want to know what the unique values are in a column, without the counts, you can use .unique().

python
# Find the unique teams
print(df['team'].unique())

Output:

scheme
['Avengers' 'Other']

This gives you a simple array of the unique values. It's great for when you need to see all the possible categories for a feature.


๐Ÿ“š References for Extra Reading

Challenge

You have been provided with a hypothetical Pandas DataFrame named sales_df. This DataFrame contains e-commerce sales data with the following columns: OrderID, Product, Category, Price, Quantity, OrderDate, and Region.

Your task is to write a sequence of Python commands to perform an initial exploratory data analysis on this DataFrame. Write one command for each of the following tasks, in the specified order.

Expected result

Your solution should consist of eight lines of Python code, each corresponding to one of the tasks. The correct code for each task is as follows:

  1. sales_df.shape
  2. sales_df.columns
  3. sales_df.head(7)
  4. sales_df.sample(10)
  5. sales_df.info()
  6. sales_df.describe()
  7. sales_df['Category'].unique()
  8. sales_df['Region'].value_counts()
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.