Loading and Viewing Data in Pandas

Introduction

Hello and welcome to our journey into data analysis with Python and pandas. Today we'll discover pandas DataFrames and learn about Loading and Viewing Data.

Pandas, a fantastic Python library, simplifies data manipulation and analysis. Our focus today is DataFrames — the go-to structure in pandas for data handling.

We will read data from different sources using pandas, load it into a DataFrame, and then explore this data. Let's begin!

Installing and Importing pandas

Installing and importing the pandas library is like getting our recipe book ready before we start cooking. In our CodeSignal kitchen, pandas comes pre-installed. To open the book, we just need to import pandas into our script. It's as simple as:

import pandas as pd  # Pandas successfully imported

This line sets a short alias, pd, for pandas so we don't have to write out pandas each time we use it.

Introduction to DataFrames

In pandas, a DataFrame is like a table, with the data as the dishes on the table. Creating a DataFrame out of a list or a dictionary is a snap with pandas. Here's how:

import pandas as pd

# From a list
data_list = ['apple', 'banana', 'cherry']
df_list = pd.DataFrame(data_list, columns=['Fruit'])
print(df_list)
# Output:
#    Fruit
# 0  apple
# 1  banana
# 2  cherry

Creating from Dictionary

And here is how to create a dataframe from dictionary:

# From a dictionary
data_dict = {'Fruit': ['apple', 'banana', 'cherry'], 'Count': [10, 20, 15]}
df_dict = pd.DataFrame(data_dict)
print(df_dict)
# Output:
#     Fruit  Count
# 0   apple     10
# 1  banana     20
# 2  cherry     15

Viewing Data in a DataFrame: Head and Tail

Now that we have our data in a DataFrame, how do we look at it and understand it? Pandas provides us with methods like head(), tail(), and info(). Here's how to use them:

# First 5 rows
print(df.head())  # Output: First 5 rows of DataFrame 'df'

# Last 5 rows
print(df.tail())  # Output: Last 5 rows of DataFrame 'df'

In our case, we have just three rows in the dataframe, so both head() and tail() will simply output the whole dataframe. However, for real data with lots of rows, they are quite useful!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal