Pandas
Pandas
ageron/handson-ml2 Public
handson-ml2 / tools_pandas.ipynb
ageron Replace 'Open in Colab' button d1d56f7 · 4 years ago
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 1/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Tools - pandas
The pandas library provides high-performance, easy-to-use data structures and
data analysis tools. The main data structure is the DataFrame , which you can
think of as an in-memory 2D table (like a spreadsheet, with column names and row
labels). Many features available in Excel are available programmatically, such as
creating pivot tables, computing columns based on other columns, plotting graphs,
etc. You can also group rows by column value, or join tables much like in SQL.
Pandas is also great at handling time series.
Prerequisites:
NumPy – if you are not familiar with NumPy, we recommend that you go
through the NumPy tutorial now.
Open in Colab Open in Kaggle
Setup
First, let's import pandas . People usually import it as pd :
In [1]:
import pandas as pd
Series objects
The pandas library contains these useful data structures:
Series objects, that we will discuss now. A Series object is 1D array,
similar to a column in a spreadsheet (with a column name and row labels).
DataFrame objects. This is a 2D table, similar to a spreadsheet (with column
names and row labels).
Panel objects. You can see a Panel as a dictionary of DataFrame s.
These are less used, so we will not discuss them here.
Creating a Series
Let's start by creating our first Series object!
In [2]:
s = pd.Series([2,-1,3,5])
s
Out[2]: 0 2
1 -1
2 3
3 5
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 2/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
dtype: int64
Similar to a 1D ndarray
Series objects behave much like one-dimensional NumPy ndarray s, and you
can often pass them as parameters to NumPy functions:
In [3]:
import numpy as np
np.exp(s)
Out[3]: 0 7.389056
1 0.367879
2 20.085537
3 148.413159
dtype: float64
Arithmetic operations on Series are also possible, and they apply elementwise,
just like for ndarray s:
In [4]:
s + [1000,2000,3000,4000]
Out[4]: 0 1002
1 1999
2 3003
3 4005
dtype: int64
Similar to NumPy, if you add a single number to a Series , that number is added
to all items in the Series . This is called * broadcasting*:
In [5]:
s + 1000
Out[5]: 0 1002
1 999
2 1003
3 1005
dtype: int64
The same is true for all binary operations such as * or / , and even conditional
operations:
In [6]:
s < 0
Out[6]: 0 False
1 True
2 False
3 False
dtype: bool
Index labels
Each item in a Series object has a unique identifier called the index label. By
default, it is simply the rank of the item in the Series (starting at 0 ) but you can
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 3/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
also set the index labels manually:
In [7]:
s2 = pd.Series([68, 83, 112, 68], index=["alice", "bob", "charles", "da
s2
Out[7]: alice 68
bob 83
charles 112
darwin 68
dtype: int64
Out[8]: 83
You can still access the items by integer location, like in a regular array:
In [9]:
s2[1]
Out[9]: 83
handson-ml2
In [10]:
/ tools_pandas.ipynb Top
s2.loc["bob"]
Preview Code
83
Blame Raw
Out[10]:
In [11]:
s2.iloc[1]
Out[11]: 83
Out[12]: bob 83
charles 112
dtype: int64
This can lead to unexpected results when using the default numeric labels, so be
careful:
In [13]:
surprise = pd.Series([1000, 1001, 1002, 1003])
surprise
Out[13]: 0 1000
1 1001
2 1002
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 4/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
3 1003
dtype: int64
In [14]:
surprise_slice = surprise[2:]
surprise_slice
Out[14]: 2 1002
3 1003
dtype: int64
Oh look! The first element has index label 2 . The element with index label 0 is
absent from the slice:
In [15]:
try:
surprise_slice[0]
except KeyError as e:
print("Key error:", e)
Key error: 0
But remember that you can access elements by integer location using the iloc
attribute. This illustrates another reason why it's always better to use loc and
iloc to access Series objects:
In [16]:
surprise_slice.iloc[0]
Out[16]: 1002
Out[17]: alice 68
bob 83
colin 86
darwin 68
dtype: int64
You can control which elements you want to include in the Series and in what
order by explicitly specifying the desired index :
In [18]:
s4 = pd.Series(weights, index = ["colin", "alice"])
s4
Out[18]: colin 86
alice 68
dtype: int64
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 5/47
04/01/2025, 20:05
s2 + s3
The resulting Series contains the union of index labels from s2 and s3 . Since
"colin" is missing from s2 and "charles" is missing from s3 , these items
have a NaN result value. (ie. Not-a-Number means missing).
Automatic alignment is very handy when working with data that may come from
various sources with varying structure and missing items. But if you forget to set
the right index labels, you can have surprising results:
In [20]:
s5 = pd.Series([1000,1000,1000,1000])
print("s2 =", s2.values)
print("s5 =", s5.values)
s2 + s5
s2 = [ 68 83 112 68]
s5 = [1000 1000 1000 1000]
Out[20]: alice NaN
bob NaN
charles NaN
darwin NaN
0 NaN
1 NaN
2 NaN
3 NaN
dtype: float64
Pandas could not align the Series , since their labels do not match at all, hence
the full NaN result.
Out[21]: life 42
universe 42
everything 42
dtype: int64
Series name
A Series can have a name :
In [22]:
s6 = pd.Series([83, 68], index=["bob", "alice"], name="weights")
s6
Out[22]: bob 83
alice 68
Name: weights, dtype: int64
Plotting a Series
Pandas makes it easy to plot Series data using matplotlib (for more details on
matplotlib, check out the matplotlib tutorial). Just import matplotlib and call the
plot() method:
In [23]:
%matplotlib inline
import matplotlib.pyplot as plt
temperatures = [4.4,5.1,6.1,6.2,6.1,6.1,5.7,5.2,4.7,4.1,3.9,3.5]
s7 = pd.Series(temperatures, name="Temperature")
s7.plot()
plt.show()
There are many options for plotting your data. It is not necessary to list them all
here: if you need a particular type of plot (histograms, pie charts, etc.), just look for
it in the excellent Visualization section of pandas' documentation, and look at the
example code.
Handling time
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 7/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Time range
Let's start by creating a time series using pd.date_range() . This returns a
DatetimeIndex containing one datetime per hour for 12 hours starting on
October 29th 2016 at 5:30pm.
In [24]:
dates = pd.date_range('2016/10/29 5:30pm', periods=12, freq='H')
dates
plt.grid(True)
plt.show()
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 8/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Resampling
Pandas lets us resample a time series very simply. Just call the resample()
method and specify a new frequency:
In [27]:
temp_series_freq_2H = temp_series.resample("2H")
temp_series_freq_2H
The resampling operation is actually a deferred operation, which is why we did not
get a Series object, but a DatetimeIndexResampler object instead. To
actually perform the resampling operation, we can simply call the mean()
method: Pandas will compute the mean of every pair of consecutive hours:
In [28]:
temp_series_freq_2H = temp_series_freq_2H.mean()
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 9/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Note how the values have automatically been aggregated into 2-hour periods. If we
look at the 6-8pm period, for example, we had a value of 5.1 at 6:30pm, and
6.1 at 7:30pm. After resampling, we just have one value of 5.6 , which is the
mean of 5.1 and 6.1 . Rather than computing the mean, we could have used
any other aggregation function, for example we can decide to keep the minimum
value of each period:
In [30]:
temp_series_freq_2H = temp_series.resample("2H").min()
temp_series_freq_2H
One solution is to fill the gaps by interpolating. We just call the interpolate()
method. The default is to use linear interpolation, but we can also select another
method, such as cubic interpolation:
In [33]:
temp_series_freq_15min = temp_series.resample("15Min").interpolate(meth
temp_series_freq_15min.head(n=10)
In [34]:
temp_series.plot(label="Period: 1 hour")
temp_series_freq_15min.plot(label="Period: 15 minutes")
plt.legend()
plt.show()
Timezones
By default datetimes are naive: they are not aware of timezones, so 2016-10-30
02:30 might mean October 30th 2016 at 2:30am in Paris or in New York. We can
make datetimes timezone aware by calling the tz_localize() method:
In [35]:
temp_series_ny = temp_series.tz_localize("America/New_York")
temp_series_ny
Note that -04:00 is now appended to all the datetimes. This means that these
datetimes refer to UTC - 4 hours.
We can convert these datetimes to Paris time like this:
In [36]:
temp_series_paris = temp_series_ny.tz_convert("Europe/Paris")
temp_series_paris
You may have noticed that the UTC offset changes from +02:00 to +01:00 : this
is because France switches to winter time at 3am that particular night (time goes
back to 2am). Notice that 2:30am occurs twice! Let's go back to a naive
representation (if you log some data hourly using local time, without storing the
timezone, you might get something like this):
In [37]:
temp_series_paris_naive = temp_series_paris.tz_localize(None)
temp_series_paris_naive
Now 02:30 is really ambiguous. If we try to localize these naive datetimes to the
Paris timezone, we get an error:
In [38]:
t
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 12/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [38]:
try:
temp_series_paris_naive.tz_localize("Europe/Paris")
except Exception as e:
print(type(e))
print(e)
<class 'pytz.exceptions.AmbiguousTimeError'>
Cannot infer dst time from Timestamp('2016-10-30 02:30:00'), try using t
he 'ambiguous' argument
Fortunately using the ambiguous argument we can tell pandas to infer the right
DST (Daylight Saving Time) based on the order of the ambiguous timestamps:
In [39]:
temp_series_paris_naive.tz_localize("Europe/Paris", ambiguous="infer")
Periods
The pd.period_range()function returns a PeriodIndex instead of a
DatetimeIndex . For example, let's get all quarters in 2016 and 2017:
In [40]:
quarters = pd.period_range('2016Q1', periods=8, freq='Q')
quarters
In [41]:
quarters + 3
The asfreq() method lets us change the frequency of the PeriodIndex . All
periods are lengthened or shortened accordingly. For example, let's convert all the
quarterly periods to monthly periods (zooming in):
In [42]:
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 13/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [42]:
quarters.asfreq("M")
By default, the asfreq zooms on the end of each period. We can tell it to zoom
on the start of each period instead:
In [43]:
quarters.asfreq("M", how="start")
In [46]:
quarterly_revenue.plot(kind="line")
plt.show()
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 14/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Pandas also provides many other time-related functions that we recommend you
check out in the documentation. To whet your appetite, here is one way to get the
last business day of each month in 2016, at 9am:
In [49]:
months_2016 = pd.period_range("2016", periods=12, freq="M")
one_day_after_last_days = months_2016.asfreq("D") + 1
last_bdays = one_day_after_last_days.to_timestamp() - pd.tseries.offset
last_bdays.to_period("H") + 9
DataFrame objects
A DataFrame object represents a spreadsheet, with cell values, column names and
row index labels. You can define expressions to compute columns based on other
columns create pivot tables group rows draw graphs etc You can see
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 15/47
04/01/2025, 20:05
columns, create pivot-tables, group rows, draw graphs, etc. You can see
handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Creating a DataFrame
You can create a DataFrame by passing a dictionary of Series objects:
In [50]:
people_dict = {
"weight": pd.Series([68, 83, 112], index=["alice", "bob", "charles"
"birthyear": pd.Series([1984, 1985, 1992], index=["bob", "alice", "
"children": pd.Series([0, 3], index=["charles", "bob"]),
"hobby": pd.Series(["Biking", "Dancing"], index=["alice", "bob"]),
}
people = pd.DataFrame(people_dict)
people
You can access columns pretty much as you would expect. They are returned as
Series objects:
In [51]:
people["birthyear"]
Multi-indexing
If all columns are tuples of the same size, then they are understood as a multi-
index. The same goes for row index labels. For example:
In [58]:
d5 = pd.DataFrame(
{
("public", "birthyear"):
{("Paris","alice"):1985, ("Paris","bob"): 1984, ("London","char
("public", "hobby"):
{("Paris","alice"):"Biking", ("Paris","bob"): "Dancing"},
("private", "weight"):
{("Paris","alice"):68, ("Paris","bob"): 83, ("London","charles"
("private", "children"):
{("Paris", "alice"):np.nan, ("Paris","bob"): 3, ("London","char
}
)
d5
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 18/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [60]:
d5["public", "hobby"] # Same result as d5["public"]["hobby"]
Dropping a level
Let's look at d5 again:
In [61]:
d5
Transposing
You can swap columns and indices using the T attribute:
In [63]:
d6 = d5.T
d6
In [65]:
d8 = d7.unstack()
d8
The stack() and unstack() methods let you select the level to
stack/unstack. You can even stack/unstack multiple levels at once:
In [67]:
d10 = d9.unstack(level = (0,1))
d10
Accessing rows
Let's go back to the people DataFrame :
In [68]:
people
You can also access rows by integer location using the iloc attribute:
In [70]:
people.iloc[2]
You can also get a slice of rows, and this returns a DataFrame object:
In [71]:
people.iloc[1:3]
people
In [76]:
birthyears
When you add a new colum, it must have the same number of rows. Missing rows
are filled with NaN, and extra rows are ignored:
In [77]:
people["pets"] = pd.Series({"bob": 0, "charles": 5, "eugene":1}) # ali
people
Out[79]:
hobby height weight age over
30 pets body_mass_index has_pets
alice Biking 172 68 33 True NaN 22.985398 False
bob Dancing 181 83 34 True 0.0 25.335002 False
charles NaN 185 112 26 False 5.0 32.724617 True
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 24/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Note that you cannot access columns created within the same assignment:
In [80]:
try:
people.assign(
body_mass_index = people["weight"] / (people["height"] / 100) *
overweight = people["body_mass_index"] > 25
)
except KeyError as e:
print("Key error:", e)
Out[81]:
hobby height weight age over
30 pets body_mass_index overweight
alice Biking 172 68 33 True NaN 22.985398 False
bob Dancing 181 83 34 True 0.0 25.335002 True
charles NaN 185 112 26 False 5.0 32.724617 True
Having to create a temporary variable d6 is not very convenient. You may want to
just chain the assigment calls, but it does not work because the people object is
not actually modified by the first assignment:
In [82]:
try:
(people
.assign(body_mass_index = people["weight"] / (people["height"]
.assign(overweight = people["body_mass_index"] > 25)
)
except KeyError as e:
print("Key error:", e)
But fear not, there is a simple solution. You can pass a function to the assign()
method (typically a lambda function), and this function will be called with the
DataFrame as a parameter:
In [83]:
(people
.assign(body_mass_index = lambda df: df["weight"] / (df["height"]
.assign(overweight = lambda df: df["body_mass_index"] > 25)
)
Out[83]:
hobby height weight age over
30 pets body_mass_index overweight
alice Biking 172 68 33 True NaN 22.985398 False
bob Dancing 181 83 34 True 0.0 25.335002 True
charles NaN 185 112 26 False 5.0 32.724617 True
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 25/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Problem solved!
Evaluating an expression
A great feature supported by pandas is expression evaluation. This relies on the
numexpr library which must be installed.
In [84]:
people.eval("weight / (height/100) ** 2 > 25")
Out[86]:
hobby height weight age over
30 pets body_mass_index overweight
alice Biking 172 68 33 True NaN 22.985398 False
bob Dancing 181 83 34 True 0.0 25.335002 False
charles NaN 185 112 26 False 5.0 32.724617 True
Querying a DataFrame
The query() method lets you filter a DataFrame based on a query expression:
In [87]:
people.query("age > 30 and pets == 0")
Out[87]:
hobby height weight age over
30 pets body_mass_index overweight
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 26/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Sorting a DataFrame
You can sort a DataFrame by calling its sort_index method. By default it
sorts the rows by their index label, in ascending order, but let's reverse the order:
In [88]:
people.sort_index(ascending=False)
Out[88]:
hobby height weight age over
30 pets body_mass_index overweight
charles NaN 185 112 26 False 5.0 32.724617 True
bob Dancing 181 83 34 True 0.0 25.335002 False
alice Biking 172 68 33 True NaN 22.985398 False
Note that returned a sorted copy of the DataFrame . To modify
sort_index
people directly, we can set the inplace argument to True . Also, we can sort
the columns instead of the rows by setting axis=1 :
In [89]:
people.sort_index(axis=1, inplace=True)
people
Out[89]:
age body_mass_index height hobby over
30 overweight pets weight
alice 33 22.985398 172 Biking True False NaN 68
bob 34 25.335002 181 Dancing True False 0.0 83
charles 26 32.724617 185 NaN False True 5.0 112
To sort the DataFrame by the values instead of the labels, we can use
sort_values and specify the column to sort by:
In [90]:
people.sort_values(by="age", inplace=True)
people
Out[90]:
age body_mass_index height hobby over
30 overweight pets weight
charles 26 32.724617 185 NaN False True 5.0 112
alice 33 22.985398 172 Biking True False NaN 68
bob 34 25.335002 181 Dancing True False 0.0 83
Plotting a DataFrame
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 27/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Just like for Series , pandas makes it easy to draw nice graphs based on a
DataFrame .
For example, it is trivial to create a line plot from a DataFrame 's data by calling
its plot method:
In [91]:
people.plot(kind = "line", x = "body_mass_index", y = ["height", "weigh
plt.show()
You can pass extra arguments supported by matplotlib's functions. For example,
we can create scatterplot and pass it a list of sizes using the s argument of
matplotlib's scatter() function:
In [92]:
people.plot(kind = "scatter", x = "height", y = "weight", s=[40, 120, 2
plt.show()
Again, there are way too many options to list here: the best option is to scroll
through the Visualization page in pandas' documentation, find the plot you are
interested in and look at the example code.
Operations on DataFrame s
lh h D F d
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb i ik h f 28/47
Although DataFrame s do not try to mimick NumPy arrays, there are a few
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [97]:
grades.mean()
The all method is also an aggregation operation: it checks whether all values are
True or not. Let's see during which months all students got a grade greater than
5 :
In [98]:
(grades > 5).all()
Most of these functions take an optional axis parameter which lets you specify
along which axis of the DataFrame you want the operation executed. The default
is axis=0 , meaning that the operation is executed vertically (on each column).
You can set axis=1 to execute the operation horizontally (on each row). For
example, let's find out which students had all grades greater than 5 :
In [99]:
(grades > 5).all(axis = 1)
The any method returns True if any value is True. Let's see who got at least
one grade 10:
In [100…
(grades == 10).any(axis = 1)
If you add a Series object to a DataFrame (or execute any other binary
operation), pandas attempts to broadcast the operation to all rows in the
DataFrame . This only works if the Series has the same size as the
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 30/47
04/01/2025, 20:05 y handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
DataFrame s rows. For example, let's subtract the mean of the DataFrame (a
Series object) from the DataFrame :
In [101…
grades - grades.mean() # equivalent to: grades - [7.75, 8.75, 7.50]
In [102…
pd.DataFrame([[7.75, 8.75, 7.50]]*4, index=grades.index, columns=grades
Automatic alignment
Similar to Series , when operating on multiple DataFrame s, pandas
automatically aligns them by row index label, but also by column names. Let's
create a DataFrame with bonus points for each person from October to
December:
In [104…
bonus_array = np.array([[0,np.nan,2],[np.nan,1,0],[0, 1, 0], [3, 3, 0]]
bonus_points = pd.DataFrame(bonus_array, columns=["oct", "nov", "dec"],
bonus_points
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 31/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [107…
fixed_bonus_points = bonus_points.fillna(0)
fixed_bonus_points.insert(0, "sep", 0)
fixed_bonus_points.loc["alice"] = 0
grades + fixed_bonus_points
In [108…
bonus_points
In [110…
better_bonus_points = bonus_points.copy()
better_bonus_points.insert(0, "sep", 0)
better_bonus_points.loc["alice"] = 0
better_bonus_points = better_bonus_points.interpolate(axis=1)
better_bonus_points
are making up bonus points, but we can't reasonably make up grades (well I guess
some teachers probably do). So let's call the dropna() method to get rid of rows
that are full of NaN s:
In [113…
final_grades_clean = final_grades.dropna(how="all")
final_grades_clean
In [114…
final_grades_clean = final_grades_clean.dropna(axis=1, how="all")
final_grades_clean
Pivot tables
Pandas supports spreadsheet-like pivot tables that allow quick data
summarization. To illustrate this, let's create a simple DataFrame :
In [118…
bonus_points
Overview functions
When dealing with large DataFrames , it is useful to get a quick overview of its
content. Pandas offers a few functions for this. First, let's create a large
DataFrame with a mix of numeric values, missing values and text values. Notice
how Jupyter displays only the corners of the DataFrame :
In [124…
much_data = np.fromfunction(lambda x,y: (x+y*y)%17*11, (10000, 26))
large_df = pd.DataFrame(much_data, columns=list("ABCDEFGHIJKLMNOPQRSTUV
large_df[large_df % 16 == 0] = np.nan
large_df.insert(3,"some_text", "Blabla")
large_df
O t[124 A B C
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb
D E F G H I 38/47
A B C some_text D E F G H I ...
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Out[124…
0 NaN 11.0 44.0 Blabla 99.0 NaN 88.0 22.0 165.0 143.0 ..
1 11.0 22.0 55.0 Blabla 110.0 NaN 99.0 33.0 NaN 154.0 ..
2 22.0 33.0 66.0 Blabla 121.0 11.0 110.0 44.0 NaN 165.0 ..
3 33.0 44.0 77.0 Blabla 132.0 22.0 121.0 55.0 11.0 NaN ..
4 44.0 55.0 88.0 Blabla 143.0 33.0 132.0 66.0 22.0 NaN ..
5 55.0 66.0 99.0 Blabla 154.0 44.0 143.0 77.0 33.0 11.0 ..
6 66.0 77.0 110.0 Blabla 165.0 55.0 154.0 88.0 44.0 22.0 ..
7 77.0 88.0 121.0 Blabla NaN 66.0 165.0 99.0 55.0 33.0 ..
8 88.0 99.0 132.0 Blabla NaN 77.0 NaN 110.0 66.0 44.0 ..
9 99.0 110.0 143.0 Blabla 11.0 88.0 NaN 121.0 77.0 55.0 ..
10 110.0 121.0 154.0 Blabla 22.0 99.0 11.0 132.0 88.0 66.0 ..
11 121.0 132.0 165.0 Blabla 33.0 110.0 22.0 143.0 99.0 77.0 ..
12 132.0 143.0 NaN Blabla 44.0 121.0 33.0 154.0 110.0 88.0 ..
13 143.0 154.0 NaN Blabla 55.0 132.0 44.0 165.0 121.0 99.0 ..
14 154.0 165.0 11.0 Blabla 66.0 143.0 55.0 NaN 132.0 110.0 ..
15 165.0 NaN 22.0 Blabla 77.0 154.0 66.0 NaN 143.0 121.0 ..
16 NaN NaN 33.0 Blabla 88.0 165.0 77.0 11.0 154.0 132.0 ..
17 NaN 11.0 44.0 Blabla 99.0 NaN 88.0 22.0 165.0 143.0 ..
18 11.0 22.0 55.0 Blabla 110.0 NaN 99.0 33.0 NaN 154.0 ..
19 22.0 33.0 66.0 Blabla 121.0 11.0 110.0 44.0 NaN 165.0 ..
20 33.0 44.0 77.0 Blabla 132.0 22.0 121.0 55.0 11.0 NaN ..
21 44.0 55.0 88.0 Blabla 143.0 33.0 132.0 66.0 22.0 NaN ..
22 55.0 66.0 99.0 Blabla 154.0 44.0 143.0 77.0 33.0 11.0 ..
23 66.0 77.0 110.0 Blabla 165.0 55.0 154.0 88.0 44.0 22.0 ..
24 77.0 88.0 121.0 Blabla NaN 66.0 165.0 99.0 55.0 33.0 ..
25 88.0 99.0 132.0 Blabla NaN 77.0 NaN 110.0 66.0 44.0 ..
26 99.0 110.0 143.0 Blabla 11.0 88.0 NaN 121.0 77.0 55.0 ..
27 110.0 121.0 154.0 Blabla 22.0 99.0 11.0 132.0 88.0 66.0 ..
28 121.0 132.0 165.0 Blabla 33.0 110.0 22.0 143.0 99.0 77.0 ..
29 132.0 143.0 NaN Blabla 44.0 121.0 33.0 154.0 110.0 88.0 ..
... ... ... ... ... ... ... ... ... ... ... ..
9970 88.0 99.0 132.0 Blabla NaN 77.0 NaN 110.0 66.0 44.0 ..
9971 99.0 110.0 143.0 Blabla 11.0 88.0 NaN 121.0 77.0 55.0 ..
9972 110.0 121.0 154.0 Blabla 22.0 99.0 11.0 132.0 88.0 66.0 ..
9973 121.0 132.0 165.0 Blabla 33.0 110.0 22.0 143.0 99.0 77.0 ..
9974 132 0 143 0 NaN
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb
Blabla 44 0 121 0 33 0 154 0 110 0 88 0 39/47
04/01/2025, 20:05
9974 132.0 143.0 NaN Blabla 44.0 121.0 33.0 154.0 110.0
handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
88.0 ..
9975 143.0 154.0 NaN Blabla 55.0 132.0 44.0 165.0 121.0 99.0 ..
9976 154.0 165.0 11.0 Blabla 66.0 143.0 55.0 NaN 132.0 110.0 ..
9977 165.0 NaN 22.0 Blabla 77.0 154.0 66.0 NaN 143.0 121.0 ..
9978 NaN NaN 33.0 Blabla 88.0 165.0 77.0 11.0 154.0 132.0 ..
9979 NaN 11.0 44.0 Blabla 99.0 NaN 88.0 22.0 165.0 143.0 ..
9980 11.0 22.0 55.0 Blabla 110.0 NaN 99.0 33.0 NaN 154.0 ..
9981 22.0 33.0 66.0 Blabla 121.0 11.0 110.0 44.0 NaN 165.0 ..
9982 33.0 44.0 77.0 Blabla 132.0 22.0 121.0 55.0 11.0 NaN ..
9983 44.0 55.0 88.0 Blabla 143.0 33.0 132.0 66.0 22.0 NaN ..
9984 55.0 66.0 99.0 Blabla 154.0 44.0 143.0 77.0 33.0 11.0 ..
9985 66.0 77.0 110.0 Blabla 165.0 55.0 154.0 88.0 44.0 22.0 ..
9986 77.0 88.0 121.0 Blabla NaN 66.0 165.0 99.0 55.0 33.0 ..
9987 88.0 99.0 132.0 Blabla NaN 77.0 NaN 110.0 66.0 44.0 ..
9988 99.0 110.0 143.0 Blabla 11.0 88.0 NaN 121.0 77.0 55.0 ..
9989 110.0 121.0 154.0 Blabla 22.0 99.0 11.0 132.0 88.0 66.0 ..
9990 121.0 132.0 165.0 Blabla 33.0 110.0 22.0 143.0 99.0 77.0 ..
9991 132.0 143.0 NaN Blabla 44.0 121.0 33.0 154.0 110.0 88.0 ..
9992 143.0 154.0 NaN Blabla 55.0 132.0 44.0 165.0 121.0 99.0 ..
9993 154.0 165.0 11.0 Blabla 66.0 143.0 55.0 NaN 132.0 110.0 ..
9994 165.0 NaN 22.0 Blabla 77.0 154.0 66.0 NaN 143.0 121.0 ..
9995 NaN NaN 33.0 Blabla 88.0 165.0 77.0 11.0 154.0 132.0 ..
9996 NaN 11.0 44.0 Blabla 99.0 NaN 88.0 22.0 165.0 143.0 ..
9997 11.0 22.0 55.0 Blabla 110.0 NaN 99.0 33.0 NaN 154.0 ..
9998 22.0 33.0 66.0 Blabla 121.0 11.0 110.0 44.0 NaN 165.0 ..
9999 33.0 44.0 77.0 Blabla 132.0 22.0 121.0 55.0 11.0 NaN ..
10000 rows × 27 columns
The head() method returns the top 5 rows:
In [125…
large_df.head()
5 rows × 27 columns
Of course there's also a tail() function to view the bottom 5 rows. You can
pass the number of rows you want:
In [126…
large_df.tail(n=2)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10000 entries, 0 to 9999
Data columns (total 27 columns):
A 8823 non-null float64
B 8824 non-null float64
C 8824 non-null float64
some_text 10000 non-null object
D 8824 non-null float64
E 8822 non-null float64
F 8824 non-null float64
G 8824 non-null float64
H 8822 non-null float64
I 8823 non-null float64
J 8823 non-null float64
K 8822 non-null float64
L 8824 non-null float64
M 8824 non-null float64
N 8822 non-null float64
O 8824 non-null float64
P 8824 non-null float64
Q 8824 non-null float64
R 8823 non-null float64
S 8824 non-null float64
T 8824 non-null float64
U 8824 non-null float64
V 8822 non-null float64
W 8824 non-null float64
X 8824 non-null float64
Y 8822 non-null float64
Z 8823 non-null float64
dtypes: float64(26), object(1)
memory usage: 2.1+ MB
Finally, the describe() method gives a nice overview of the main aggregated
values over each column:
count : number of non-null (not NaN) values
mean : mean of non-null values
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 41/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [128…
large_df.describe()
Out[128… A B C D E
count 8823.000000 8824.000000 8824.000000 8824.000000 8822.000000 882
mean 87.977559 87.972575 87.987534 88.012466 87.983791 8
std 47.535911 47.535523 47.521679 47.521679 47.535001
min 11.000000 11.000000 11.000000 11.000000 11.000000 1
25% 44.000000 44.000000 44.000000 44.000000 44.000000 4
50% 88.000000 88.000000 88.000000 88.000000 88.000000 8
75% 132.000000 132.000000 132.000000 132.000000 132.000000 13
max 165.000000 165.000000 165.000000 165.000000 165.000000 16
8 rows × 26 columns
In [129…
my_df = pd.DataFrame(
[["Biking", 68.5, 1985, np.nan], ["Dancing", 83.1, 1984, 3]],
columns=["hobby","weight","birthyear","children"],
index=["alice", "bob"]
)
my_df
Saving
Let's save it to CSV, HTML and JSON:
In [130…
my_df.to_csv("my_df.csv")
my_df.to_html("my_df.html")
my_df.to_json("my_df.json")
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 42/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
# my_df.csv
,hobby,weight,birthyear,children
alice,Biking,68.5,1985,
bob,Dancing,83.1,1984,3.0
# my_df.html
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>hobby</th>
<th>weight</th>
<th>birthyear</th>
<th>children</th>
</tr>
</thead>
<tbody>
<tr>
<th>alice</th>
<td>Biking</td>
<td>68.5</td>
<td>1985</td>
<td>NaN</td>
</tr>
<tr>
<th>bob</th>
<td>Dancing</td>
<td>83.1</td>
<td>1984</td>
<td>3.0</td>
</tr>
</tbody>
</table>
# my_df.json
{"hobby":{"alice":"Biking","bob":"Dancing"},"weight":{"alice":68.5,"bo
b":83.1},"birthyear":{"alice":1985,"bob":1984},"children":{"alice":nul
l,"bob":3.0}}
Note that the index is saved as the first column (with no name) in a CSV file, as
<th> tags in HTML and as keys in JSON.
Saving to other formats works very similarly, but some formats require extra
libraries to be installed. For example, saving to Excel requires the openpyxl library:
In [132…
try:
my_df.to_excel("my_df.xlsx", sheet_name='People')
except ImportError as e:
print(e)
N d l d ' l'
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 43/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
No module named 'openpyxl'
Loading
Now let's load our CSV file back into a DataFrame :
In [133…
my_df_loaded = pd.read_csv("my_df.csv", index_col=0)
my_df_loaded
Combining DataFrame s
SQL-like joins
One powerful feature of pandas is it's ability to perform SQL-like joins on
DataFrame s. Various types of joins are supported: inner joins, left/right outer
joins and full joins. To illustrate this, let's start by creating a couple simple
DataFrame s:
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 44/47
04/01/2025, 20:05 handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
In [135…
city_loc = pd.DataFrame(
[
["CA", "San Francisco", 37.781334, -122.416728],
["NY", "New York", 40.705649, -74.008344],
["FL", "Miami", 25.791100, -80.320733],
["OH", "Cleveland", 41.473508, -81.739791],
["UT", "Salt Lake City", 40.755851, -111.896657]
], columns=["state", "city", "lat", "lng"])
city_loc
In [136…
city_pop = pd.DataFrame(
[
[808976, "San Francisco", "California"],
[8363710, "New York", "New-York"],
[413201, "Miami", "Florida"],
[2242193, "Houston", "Texas"]
], index=[3,4,5,6], columns=["population", "city", "state"])
city_pop
you want a FULL OUTER JOIN , where no city gets dropped and NaN values are
added, you must specify how="outer" :
In [138…
all_cities = pd.merge(left=city_loc, right=city_pop, on="city", how="ou
all_cities
C t ti
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 46/47
04/01/2025, 20:05
Concatenation handson-ml2/tools_pandas.ipynb at master · ageron/handson-ml2 · GitHub
Rather than joining DataFrame s, we may just want to concatenate them. That's
what concat() is for:
In [141…
result_concat = pd.concat([city_loc, city_pop])
result_concat
https://github.com/ageron/handson-ml2/blob/master/tools_pandas.ipynb 47/47