Lesson

A Table in pandas: Reading, Selecting and Filtering

Read 398 real car models into a pandas table: a first look, a column as a Series, rows by label and by position, filtering with conditions, sorting and counting, and the same question in SQL and in pandas.

Last updated:


In this lesson we learn how pandas reads a CSV file into a table in memory, how we select columns and rows by name and by position, and how we keep, sort and count the rows that meet a condition.
At the end we compare a question known from SQL with the same question in pandas.

The most fuel-efficient models

The 398 car models of 1970 to 1982 are the data of NumPy arrays, where their fuel economy is converted to liters per 100 km and the economical ones are counted with a mask.
A buyer comparing models asks the next question: which models drive at least 35 miles on a gallon (about 6.7 liters per 100 km), and what do they have in common:
weight, cylinders, origin, year?

The array of that lesson cannot answer it. It holds only numbers, so the name and the origin of each model, which are text, were left out of it, and its columns are known by position only.
A table of pandas keeps columns of different types, each with a name.

Your hypothesis. What do you expect the models of at least 35 miles per gallon to have in common:
the weight, the number of cylinders, the origin, the year? Write down your hypothesis; after sorting and counting are taught, the section the answer to the opening question checks it against the data.

Show a hint

Think about what a car must carry and move on every kilometer.

The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other.
The first run loads pandas, so it can take a few seconds.

Reading a CSV file

pandas is a package for working with tables in Python. It is imported under the short name pd, which is the common convention.
The function pd.read_csv reads a CSV file and returns a DataFrame:
a table in memory, with a name for each column and a label for each row.
The attribute shape is the number of rows and of columns, as for an array in shape and type of a table.

import pandas as pd

cars = pd.read_csv('auto-mpg.csv')
print(cars.shape)
(398, 9)

The file is the Auto MPG data of the UCI Machine Learning Repository (CC BY 4.0, see the file description):
fuel economy in miles per gallon (mpg, the distance driven on one gallon), weight in pounds, and seven more columns.

A first look at a table

Before any question, a program checks what it has read. The method info() prints the number of rows, and for each column its name, the number of values that are not missing (Non-Null Count) and its type (Dtype).
The argument memory_usage=False leaves out a line about memory, which differs between computers; print() then ends the last line.

cars.info(memory_usage=False)
print()
<class 'pandas.DataFrame'>
RangeIndex: 398 entries, 0 to 397
Data columns (total 9 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   mpg           398 non-null    float64
 1   cylinders     398 non-null    int64  
 2   displacement  398 non-null    float64
 3   horsepower    392 non-null    float64
 4   weight        398 non-null    int64  
 5   acceleration  398 non-null    float64
 6   model_year    398 non-null    int64  
 7   origin        398 non-null    str    
 8   name          398 non-null    str    
dtypes: float64(4), int64(3), str(2)

The types: int64 whole numbers, float64 numbers with a fraction, and str text. pandas before 3.0, as on Colab today, prints the first line with pandas.core.frame.DataFrame and the type of a text column as object.

The column horsepower has 392 values: six models have no horsepower in the file. pandas writes a missing value as NaN, the nan of missing values; its methods mean(), max() and sum() skip it, and count() returns the number of values that are not missing.

The method head(n) returns the first n rows (5 when n is not given), and tail(n) the last ones.
A box shows a value in its last line even without print:

cars.head(3)
    mpg  cylinders  displacement  ...  model_year  origin                       name
0  18.0          8         307.0  ...          70     usa  chevrolet chevelle malibu
1  15.0          8         350.0  ...          70     usa          buick skylark 320
2  18.0          8         318.0  ...          70     usa         plymouth satellite

[3 rows x 9 columns]

Nine columns do not fit in the output, so pandas writes ... in place of the middle ones.
The numbers 0, 1, 2 at the left are not a column of the file but the labels of the rows.

A column and the index

A table followed by a column name in square brackets, cars['mpg'], returns that column as a Series:
a sequence of values, each with the label of its row. The labels of the rows are the index of the table; read_csv gave the rows the labels 0 to 397.
A Series has methods that summarize it, such as max(), min() and mean(), the SQL MAX, MIN and AVG.

mpg = cars['mpg']
print(mpg.head(3))
print(mpg.max(), round(mpg.mean(), 1))
0    18.0
1    15.0
2    18.0
Name: mpg, dtype: float64
46.6 23.5

In the output of head(3) the left column is the index and the right one holds the values; Name is the name of the column.

The method describe() summarizes a column of numbers in one call:
count values, the mean, the standard deviation std (a typical distance from the mean), the extremes, and the quartiles:
a quarter of the models had at most the value of 25%, half at most 50% (the median), three quarters at most 75%.

print(mpg.describe())
count    398.000000
mean      23.514573
std        7.815984
min        9.000000
25%       17.500000
50%       23.000000
75%       29.000000
max       46.600000
Name: mpg, dtype: float64

Several columns are selected with a list of names inside the square brackets, hence the two pairs of brackets.
The result is a table, a DataFrame, with only those columns:

cars[['name', 'mpg', 'origin']].head(3)
                        name   mpg origin
0  chevrolet chevelle malibu  18.0    usa
1          buick skylark 320  15.0    usa
2         plymouth satellite  18.0    usa

Practice

Your turn. For how many models does the file record the horsepower, and what is the largest horsepower?
Print the two numbers on one line, the count first, separated by a space.

# your code here
Show a hint

Select the column of the horsepower with square brackets.

Show a solution
power = cars['horsepower']
print(power.count(), power.max())
392 230.0
Show a common mistake and why it happens
power = cars['horsepower']
print(len(power), power.max())

The function len counts every row, the six without horsepower too, so it gives 398; count() counts only the values that are not missing, as in missing values.

Rows by label and by position: loc and iloc

A row can be reached by its label or by its position. loc[row, column] selects by labels, and iloc[row, column] by positions, counted from 0 as in a list; a negative position counts from the end, so column -1 is the last column, name.

print(cars.loc[322, 'name'])
print(cars.iloc[322, -1])
mazda glc
mazda glc

After read_csv the label of each row equals its position, so both lines find the same model.
They differ once rows are filtered or sorted, as the section on sorting shows.
With one index the result is a whole row: cars.iloc[322] is the row at position 322.

A slice works in both, with one difference: a slice of labels includes its end, and a slice of positions stops before its end, as in a list.

print(cars.loc[30:32, 'name'])
print(cars.iloc[30:32, -1])
30    chevrolet vega 2300
31          toyota corona
32             ford pinto
Name: name, dtype: str
30    chevrolet vega 2300
31          toyota corona
Name: name, dtype: str
lociloc
Selects bylabelspositions from 0
A slice a:bincludes bstops before b
Fits whenthe label or the name is knownthe place is known

Practice

Your turn. Print the fuel economy (miles per gallon) of the rows labelled 320 to 323, with a slice of labels.

# your code here
Show a hint

In loc the row part is a slice of two labels, and a slice of labels includes its end.

Show a solution
print(cars.loc[320:323, 'mpg'])
320    37.0
321    32.2
322    46.6
323    27.9
Name: mpg, dtype: float64
Show a common mistake and why it happens
print(cars.iloc[320:323, 0])

A slice of positions stops before its end, so iloc leaves out the row at position 323 and prints three rows.
The labels and the positions are equal in cars, so only the end differs.

Keeping the rows that meet a condition

The efficient models are the rows that meet a condition. As for an array in selecting rows with a boolean mask, a comparison returns a boolean mask and sum() counts its True values.
In pandas the mask is a Series, with the labels of the rows:

mask = cars['mpg'] >= 35
print(mask.head(3))
print(mask.sum())
0    False
1    False
2    False
Name: mpg, dtype: bool
36

A mask in the square brackets of a table keeps the rows where it is True, like WHERE in SQL:

efficient = cars[cars['mpg'] >= 35]
print(len(efficient))
print(efficient[['name', 'mpg']].head(3))
36
                                name   mpg
54                       datsun 1200  35.0
218                    renault 5 gtl  36.0
244  volkswagen rabbit custom diesel  43.1

The rows keep their labels from cars: the first efficient model is the row labelled 54, which is at position 0 of efficient.
A mask also fits the row part of loc: cars.loc[cars['mpg'] >= 35, 'name'] returns the names of the 36 efficient models, as a Series.

Two conditions

Masks of a table are joined as masks of an array, with & or | and parentheses around each condition, as in two conditions:

both = cars[
    (cars['mpg'] >= 35) & (cars['origin'] == 'usa')
]
efficient_mask = cars['mpg'] >= 35
american = cars['origin'] == 'usa'
either = cars[efficient_mask | american]
print(len(both), len(either))
7 278

Of the 36 efficient models, 7 are American; 278 models are efficient or American, or both.
The words and and or of Python do not join masks: they need one True or False, and a Series of 398 values has no single answer, so pandas stops with a ValueError.

The method isin tests whether each value is in a list, like IN in SQL, and ~ flips a mask, like NOT (and as in removing rows with nan):

imported = cars[cars['origin'].isin(['europe', 'japan'])]
not_four = cars[~(cars['cylinders'] == 4)]
print(len(imported), len(not_four))
149 194

Practice

Your turn. How many models from Europe or from Japan have a number of cylinders other than four?
Print the number.

# your code here
Show a hint

Make a mask of the two origins with isin.

Show a solution
abroad = cars['origin'].isin(['europe', 'japan'])
four = cars['cylinders'] == 4
print(len(cars[abroad & ~four]))
17
Show a common mistake and why it happens
abroad = cars['origin'].isin(['europe', 'japan'])
four = cars['cylinders'] == 4
print(len(cars[abroad & four]))

Without ~ the mask keeps the four-cylinder models of the two origins, 132 models, which is the opposite of what the question asks.

Sorting and counting

The method sort_values returns the table sorted by a column in ascending order; with ascending=False it sorts in descending order.
Followed by head, it is the ORDER BY ... DESC LIMIT of SQL:

top = cars.sort_values('mpg', ascending=False).head(5)
print(top[['name', 'mpg', 'model_year', 'origin']])
                     name   mpg  model_year  origin
322             mazda glc  46.6          80   japan
329   honda civic 1500 gl  44.6          80   japan
325  vw rabbit c (diesel)  44.3          80  europe
394             vw pickup  44.0          82  europe
326    vw dasher (diesel)  43.4          80  europe

The rows moved with their labels, so top.iloc[0] is the most efficient model and top.loc[322] is the same row, while top.loc[0] does not exist.

The method value_counts() of a column counts how many times each value appears, in descending order of the count.
On the 36 efficient models:

print(efficient['cylinders'].value_counts())
cylinders
4    34
5     1
6     1
Name: count, dtype: int64

To compare with the whole table we compute shares, not counts.
With normalize=True, value_counts returns the share of each value instead of its count.
The loop prints, for the efficient models and then for all of them, the shares of the origins, the mean weight in pounds, and how many models are of 1980 or later, out of how many:

for table in [efficient, cars]:
    shares = table['origin'].value_counts(normalize=True)
    print(shares.round(2))
    late = (table['model_year'] >= 80).sum()
    print(round(table['weight'].mean()), late, len(table))
origin
japan     0.50
europe    0.31
usa       0.19
Name: proportion, dtype: float64
2083 28 36
origin
usa       0.63
japan     0.20
europe    0.18
Name: proportion, dtype: float64
2970 89 398

The answer to the opening question

The 36 models of at least 35 miles per gallon have this in common:

  • Four cylinders. 34 of the 36, against 204 of all 398 models.
  • A light car. Their mean weight is 2083 pounds (about 945 kg), against 2970 pounds for all the models.
  • Late years. 28 of the 36 are of 1980 to 1982, against 89 of the 398.
  • Japan and Europe. Half of them are Japanese and 19% American, against 20% and 63% of all the models.

These are descriptions, not causes: the table does not say why the models of the 1980s were lighter, or why the American makers had fewer efficient models.

Practice

Your turn. Take the 16 models with the smallest engine displacement (the column displacement).
How many of them come from each origin? Print the count of each origin, in descending order of the count.

# your code here
Show a hint

Sort by the displacement in ascending order, the order that sort_values uses when nothing else is given.

Show a solution
small = cars.sort_values('displacement').head(16)
print(small['origin'].value_counts())
origin
japan     11
europe     5
Name: count, dtype: int64
Show a common mistake and why it happens
small = cars.sort_values('displacement', ascending=False)
small = small.head(16)
print(small['origin'].value_counts())

With ascending=False the sort starts from the largest engine, so the 16 rows are the largest engines, all of them American.

The same question in SQL and in pandas

The table daily_ridership of the SQL guide holds 731 days of the bike-share system of Washington, D.C. in 2011 and 2012.
Two queries in the SQL of that guide ask for the busiest working days and count the days with more than 7000 rides:

SELECT observation_date, total_rides
FROM daily_ridership
WHERE working_day = 1
ORDER BY total_rides DESC
LIMIT 3;

SELECT COUNT(*) FROM daily_ridership WHERE total_rides > 7000;

The file bike-share-days.csv holds the same table. In pandas the same questions are steps on variables:

days = pd.read_csv('bike-share-days.csv')
working = days[days['working_day'] == 1]
ranked = working.sort_values('total_rides', ascending=False)
print(ranked[['observation_date', 'total_rides']].head(3))
busy = days[days['total_rides'] > 7000]
print(len(busy), busy['working_day'].sum())
    observation_date  total_rides
447       2012-03-23         8362
571       2012-07-25         8173
629       2012-09-21         8167
94 70

The answers are the same; the way to them differs:

  • A table in memory. pandas read the CSV file into the program once; there is no database file and no query sent to it.
  • Intermediate results in variables. working and busy stay in the program, and the next step starts from them: the last line asked busy how many of its 94 days were working days (70) without filtering the 731 days again. In SQL each of the two questions above is a query of its own, and the second filters the whole table again.
  • SQL keeps its place. Data that stays in a database, and is updated and shared there, is asked with SQL, as in the SQL lessons.

Keep in mind

  • pd.read_csv reads a CSV file into a DataFrame, a table in memory; shape, info(), head() and describe() show what was read before any question.
  • A column, cars['mpg'], is a Series: values with the labels of their rows, the index. A list of names, cars[['a', 'b']], returns a table. NaN marks a missing value, and mean() and count() skip it.
  • loc selects by labels and its slice includes the end; iloc selects by positions and its slice stops before the end.
  • A comparison returns a boolean mask, and cars[mask] keeps the rows where it is True. Conditions are joined with &, | and ~, each condition in parentheses; isin tests a list of values.
  • sort_values with ascending=False and then head(n) returns the n largest; value_counts() counts each value, and with normalize=True it returns shares to compare with the whole table.
  • In pandas an intermediate result stays in a variable and feeds the next step; in the SQL of the comparison each question was a query of its own.