1 Pandas Practice Questions: Forty-Eight Examples to Make You an Expert
Pandas is a hugely popular tool for machine learning. It builds on the strengths and speed of Numpy to allow for mixed column types in a two-dimensional DataFrame that is indexable by column or row.
As popular as it is, Pandas offers so many different ways to do things that it helps to have examples and practice exercises to refresh our memory from time to time. Some of these will be challenging to you if you’re new to Pandas (or, like me, you’re reviewing it).
Note that in addition to Pandas, we’ll also be taking advantage of the sample data sets from Seaborn. You’ll need to be able to load one of these data sets into a DataFrame to answer many of the questions. (One solution is provided for you since it’s critical to later answers). 1
1.1 Creating Data Frames and Using Sample Data Sets
Using NumPy, create a Pandas DataFrame with five rows and three columms.
For a Pandas DataFrame created from a NumPy array, what is the default behavior for the labels for the columns? For the rows?
Create a second DataFrame as above with five rows and three columns, setting the row labels to the names of any five major US cities and the column labels to the first three months of the year.
You recall that the Seaborn package has some sample data sets built in, but can’t remember how to list and load them. Assuming the functions to do so have “data” in the name, how might you locate them? You can assume a Jupyter Notebook / IPython environment and explain the process, or write the code to do it in Python.
1.2 Loading Data From CSV
Zillow home data is available at this URL 1 or URL 2. How can you open this file as a DataFrame named df_homes in Pandas?
Save the DataFrame, df_homes, to a local CSV file, zillow_home_data.csv.
Load zillow_home_data.csv back into a new Dataframe, df_homes_2.
Compare the dimensions of the two DataFrames, df_homes and df_homes_2. Are they equal? If not, how can you fix it?
A remote spreadsheet showing how a snapshot of how traffic increased for a hypothetical website is available here: URL. Load the worksheet page of the spreasheet data labelled “February 2022” as a DataFrame named “feb“. Note: the leftmost column in the spreadsheet is the index column.
The “Month to Month Increase” column is a bit hard to understand, so ignore it for now. Given the values for “This Month” and “Last Month”, create a new column, “Percentage Increase”.
1.3 Basic Operations on Data
Using Seaborn, get a dataset about penguins into a dataframe named df_penguins. Note that because all of the following questions depend on this example, we’ll provide the solution here so no one gets stuck:
Write the code to show the the number of rows and columns in df_penguins.
How might you show the first few rows of df_penguins?
How can you return the unique species of penguins from df_penguins? How many unique species are there?
What function can we use to drop the rows that have missing data?
By default, will this modify df_penguins or will it return a copy?
How can we override the default?
Create a new DataFrame, df_penguins_full, with the missing data deleted.
What is the average bill length of a penguin, in millimeters, in this data set?
Which of the following is most strongly correlated with bill length? a) Body mass? b) Flipper length? c) Bill depth? Show how you arrived at the answer.
How could you show the median flipper length, grouped by species?
Which species as the longest flippers?
Which two species have the most similar mean weight? Show how you arrived at the answer.
How could you sort the rows by bill length?
How could you run the same sort in descending order?
How could you sort by species first, then by body mass?
1.4 Selecting Rows, Columns, and Cells
Let’s look at some precious stones now, and leave the poor penguins alone for a while.
Load the Seaborn “diamonds” dataset into a Pandas dataframe named diamonds.
Display the columns that are available.
If you select a single column from the diamonds DataFrame, what will be the type of the return value?
Select the ‘table’ column and show its type.
Select the first ten rows of the price and carat columns ten rows of the diamonds DataFrame into a variable called subset, and display them.
For a given column, show the code to display the datatype of the values in the column?
Select the first row of the diamonds DataFrame into a variable called row.
What would you expect the data type of the row to be? (Display it)
Can you discover the names of the columns using only the row returned in #33?Why or why not?
Select the row with the highest priced diamond.
Select the row with the lowest priced diamond.
1.5 Some Exercises Using Time Series
The seaborn “taxis” dataset has some datetime values for the time when the customer was picked up and dropped off.
Load the taxis dataset into a DataFrame, taxis.
The pickup column contains the date and time the customer picked up, but it’s a string. Add a column to the DataFrame, pickup_time, containing the value in pickup as a DateTime.
We have a hypothesis that as the day goes on, the tips get higher. We’ll need to wrangle the data a bit before testing this, however. First, now that we have a datetime column, pickup_time, create a subset of it to create a new DataFrame, taxis_one_day. This new DataFrame should have values between ‘2019-03-23 00:06:00’ (inclusive) and ‘2019-03-24 00:00:00’ (exlusive).
We now have a range from morning until midnight, but we to take the mean of the numeric columns, grouped at one hour intervals. Save the result as taxis_means, and display it.
Create a simple line plot of the value “distance”.
Overall, do riders seem to travel further or less far as the day progresses?
Create a new column in taxis_means, tip_in_percent. The source columns for this should be “fare” and “tip”.
Create a new column, time_interval, as a range of integer values beginning with zero.
Display the correlations between the following pairs of values:
tip_in_percent and distance.
tip_in_percent and passengers.
tip_in_percent and time_interval.
Admittedly, the size of the data set is fairly small given how we’ve subsetted it. But based on the values in #45, which of the three pairs show the strongest correlation.
Did our hypothesis that people tip more as the day goes on turn out to be warranted?
2 Panda Exercises Solutions
2.1 Creating DataFrames and Using Sample Data Sets
1
2
3
importpandasaspdimportnumpyasnpimportseabornassb
Using NumPy, create a Pandas DataFrame with five rows and three columms:
For a Pandas DataFrame created from a NumPy array, what is the default behavior for the labels for the columns? For the rows?
Both the “columns” value and the “index” value (for the rows) are set to zero based numeric arrays.
Create a second DataFrame as above with five rows and three columns, setting the row labels to the names of any five major US cities and the column labels to the first three months of the year.
You recall that the Seaborn package has some data sets built in, but can’t remember how to list and load them. Assuming the functions to do so have “data” in the name, how might you locate them? You can assume a Jupyter Notebook / IPython environment and explain the process, or write the code to do it in Python.
Method 1: In an empty code cell, type sb + tab to bring up a list of names. Type “data” to filter the names.
The “Month to Month Increase” column is a bit hard to understand, so ignore it for now. Given the values for “This Month” and “Last Month”, create a new column, “Percentage Increase”.
Using Seaborn, get a dataset about penguins into a dataframe named df_penguins. Note that because all of the following questions depend on this example, we’ll provide the solution here so no one gets stuck:
1
df_penguins=sb.load_dataset('penguins')
Write the code to show the the number of rows and columns in df_penguins
1
2
df_penguins.shape# (344, 7)
How might you show the first few rows of df_penguins?
1
df_penguins.head()
species
island
bill_length_mm
bill_depth_mm
flipper_length_mm
body_mass_g
sex
0
Adelie
Torgersen
39.1
18.7
181.0
3750.0
Male
1
Adelie
Torgersen
39.5
17.4
186.0
3800.0
Female
2
Adelie
Torgersen
40.3
18.0
195.0
3250.0
Female
3
Adelie
Torgersen
NaN
NaN
NaN
NaN
NaN
4
Adelie
Torgersen
36.7
19.3
193.0
3450.0
Female
How can you return the unique species of penguins from df_penguins? How many unique species are there?
1
2
3
4
5
6
7
8
9
10
11
species=df_penguins["species"].copy()unique=species.fillna(0)unique=unique.drop_duplicates()nrows=unique.shape[0]print(unique)print(f"There are {nrows} unique species, {list(unique.values)}.")# 0 Adelie# 152 Chinstrap# 220 Gentoo# Name: species, dtype: object# There are 3 unique species, ['Adelie', 'Chinstrap', 'Gentoo'].
What function can we use to drop the rows that have missing data?
1
df_penguins.dropna()
species
island
bill_length_mm
bill_depth_mm
flipper_length_mm
body_mass_g
sex
0
Adelie
Torgersen
39.1
18.7
181.0
3750.0
Male
1
Adelie
Torgersen
39.5
17.4
186.0
3800.0
Female
2
Adelie
Torgersen
40.3
18.0
195.0
3250.0
Female
4
Adelie
Torgersen
36.7
19.3
193.0
3450.0
Female
5
Adelie
Torgersen
39.3
20.6
190.0
3650.0
Male
…
…
…
…
…
…
…
…
338
Gentoo
Biscoe
47.2
13.7
214.0
4925.0
Female
340
Gentoo
Biscoe
46.8
14.3
215.0
4850.0
Female
341
Gentoo
Biscoe
50.4
15.7
222.0
5750.0
Male
342
Gentoo
Biscoe
45.2
14.8
212.0
5200.0
Female
343
Gentoo
Biscoe
49.9
16.1
213.0
5400.0
Male
(333 rows × 7 columns)
By default, will this modify df_penguins or will it return a copy?
It will return a copy.
How can we override the default?
We can use df_penguins.dropna(inplace=True)
Create a new DataFrame, df_penguins_full, with the missing data deleted.
Which of the following is most strongly correlated with bill length? a) Body mass? b) Flipper length? c) Bill depth? Show how you arrived at the answer.
Let’s look at some precious stones now, and leave the poor penguins alone for a while. Let’s look at some precious stones now, and leave the poor penguins alone for a while.
Load the Seaborn diamonds dataset into a Pandas dataframe named diamonds.
Select the first ten rows of the price and carat columns ten rows of the diamonds DataFrame into a variable called subset, and display them.
1
2
subset=diamonds.loc[0:9,['price','carat']]subset
price
carat
0
326
0.23
1
326
0.21
2
327
0.23
3
334
0.29
4
335
0.31
5
336
0.24
6
336
0.24
7
337
0.26
8
337
0.22
9
338
0.23
For a given column, show the code to display the datatype of the values in the column?
1
2
diamonds['price'].dtype# dtype('int64')
Select the first row of the diamonds DataFrame into a variable called row.
1
row=diamonds.iloc[0,:]
What would you expect the data type of the row to be? Display it.
A Pandas series
1
2
type(row)# pandas.core.series.Series
Can you discover the names of the columns using only the row returned in #33? Why or why not?Can you discover the names of the columns using only the row returned in #33? Why or why not?
Yes, because a row series should have the columns as the index (See below):
diamonds.loc[diamonds['price'].idxmax(),:]# carat 2.29# cut Premium# color I# clarity VS2# depth 60.8# table 60.0# price 18823# x 8.5# y 8.47# z 5.16# Name: 27749, dtype: object
Select the row with the lowest priced diamond.
1
2
3
4
5
6
7
8
9
10
11
12
diamonds.loc[diamonds['price'].idxmin(),:]# carat 0.23# cut Ideal# color E# clarity SI2# depth 61.5# table 55.0# price 326# x 3.95# y 3.98# z 2.43Name:0,dtype:object
2.5 Some Exercises Using Time Series
Load the taxis dataset into a DataFrame, taxis.
1
taxis=sb.load_dataset('taxis')
The pickup column contains the date and time the customer picked up, but it’s a string. Add a column to the DataFrame, pickup_time, containing the value in pickup as a DateTime.
We have a hypothesis that as the day goes on, the tips get higher. We’ll need to wrangle the data a bit before testing this, however. First, now that we have a datetime column, pickup_time, create a subset of it to create a new DataFrame, taxis_one_day. This new DataFrame should have values between ‘2019-03-23 06:00:00’ (inclusive) and ‘2019-03-24 00:00:00’ (exlusive).
We now have a range from morning until midnight, but we to take the mean of the numeric columns, grouped at one hour intervals. Save the result as taxis_means, and display it.
Admittedly, the size of the data set is fairly small given how we’ve subsetted it. But based on the values in #45, which of the three pairs show the strongest correlation.
tip_in_percent and passengers.
Did our hypothesis that people tip more as the day goes on turn out to be warranted?