Working with real-world data and CSV files with pandas.
For this tutorial, we will use a real-world dataset of Titanic passenger data.
titanic.csv in your current PyCharm Project.analyze_titanic.py. Import pandas# analyze_titanic.py
import pandas as pd
# Your code...read_csv function:titanic = pd.read_csv("titanic.csv")titanic:print(type(titanic))The read_csv function to read data stored as a csv file
into a pandas DataFrame. A pandas DataFrame is one of the
most powerful and widely used data structures in Python, particularly in
data science, machine learning, and data analytics. This type is made to
ease data cleaning, manipulation, alignment, grouping, and tabular
analysis.
Unlike Numpy
arrays,DataFramesare strictly 2-dimensional.
print(titanic)head function:print(titanic.head(8))tail function:print(titanic.tail(8))dtypes
attribute:print(titanic.dtypes)For each of the columns, the used data type is enlisted. The data
types in this DataFrame are integers (int64), floats
(float64) and strings (object).
DataFrame to an Excel file
(.xlsx) to share data with your colleagues:titanic.to_excel("titanic.xlsx", sheet_name="passengers", index=False)info function:print(titanic.info())We can see that:
strings, aka object). The other
columns are numerical data, some of them are whole numbers (integer) and
others are real numbers (float).The approximate amount of RAM used to hold the DataFrame is provided as well.
ages = titanic["Age"]
print(ages)To select a single column, use square brackets
[]with the column name of the column of interest.
Each column in a DataFrame is a Series. As
a single column is selected, the returned object is a pandas
Series. We can verify this by checking the type of the
output:
print(type(ages))age_sex = titanic[["Age", "Sex"]]
print(age_sex.head())The returned data type is a DataFrame! The selection
returned a DataFrame with 891 rows and 2 columns.
Remember, a
DataFrameis strictly 2-dimensional with both a row and column dimension.
above_35 = titanic[titanic["Age"] > 35]
print(above_35)
print(type(above_35))To select rows based on a conditional expression, use a condition inside the selection brackets [].
above_35:print(above_35.shape)adult_names = titanic.loc[titanic["Age"] > 35, "Name"]In this case, a subset of both rows and columns is made in one go and
just using selection brackets [] is not sufficient anymore. The
loc/iloc operators are required in front of
the selection brackets [].
When using loc/iloc, the part
before the comma is the rows you want, and the part
after the comma is the columns you want to select.
locis label-based, whileilocis integer-position-based.
titanic.iloc[9:25, 2:5]Pandas has built-in, seamless integration with Matplotlib!
pandas provides a convenient .plot() method
directly on DataFrames and Series
that acts as a wrapper around Matplotlib.
matplotlib.
Add the following import statement:import matplotlib.pyplot as pltvalue_counts function:sex = titanic[["Sex"]]
sex.value_counts().plot(kind="bar")
plt.title("Titanic Passengers by Sex")
plt.xlabel("Sex")
plt.ylabel("Count")
plt.show()(sex.value_counts(normalize=True)*100).plot(kind="bar")DataFrame to keep
only the passengers where Survived == 1:survivors = titanic[titanic["Survived"] == 1]
survivor_percentage = survivors["Sex"].value_counts(normalize=True) * 100
survivor_percentage.plot(kind="bar", color=["#2ecc71", "#3498db"])Did gender affect survival?
titanic["Age"].plot(kind="hist", bins=20, color="#3498db", edgecolor="white")
# Plot all passengers in light gray/blue
titanic["Age"].plot(kind="hist", bins=20, alpha=0.5, label="All Passengers", color="gray", edgecolor="white")
# Plot survivors on top in green
titanic[titanic["Survived"] == 1]["Age"].plot(kind="hist", bins=20, alpha=0.7, label="Survivors", color="#2ecc71", edgecolor="white")
plt.title("Age Distribution: All Passengers vs. Survivors")
plt.xlabel("Age")
plt.ylabel("Count")
plt.legend()According to the result, did age affect survival?
First, we need to group passengers by class with
the groupby function.
In pandas, groupby() is one of the most powerful and
frequently used tools for data analysis. It allows you to group
your rows together based on the values in one or more columns
so that you can perform calculations on each group
independently.
p_by_class = titanic.groupby("Pclass")
print(p_by_class.count()) # number of passengers by classLet’s select the Survival column and compute the
proportion of survivors per class:
# mean() allows to compute the percentage
pclass_survival = titanic.groupby("Pclass")["Survived"].mean() * 100
pclass_survival.plot( kind="bar", edgecolor="black")
plt.title("Survival Rate by Passenger Class")
plt.xlabel("Passenger Class (1 = 1st, 2 = 2nd, 3 = 3rd)")
plt.ylabel("Survival Rate (%)")
plt.ylim(0, 100)
plt.grid(axis="y", linestyle="--", alpha=0.6)
plt.show()So, did 1st-class passengers have a higher survival rate than 3rd-class passengers? …
Write Python instructions (directly in the console) with pandas to find the:
Use pandas to answer other interesting questions. For
example:
This tutorial is based on the following official pandas getting started tutorials: