Lecture 4: August 14th, 2023#

Announcements:

  • Student hours with Yasmeen have been set! They are Tuesdays from 12:00pm-1:30pm. The Zoom information is the same as lecture. All information is posted on the front page of Canvas.

  • Outcome quizzes are slowly being released over the course of today. The first round has a deadline set of next Monday at midnight, but remember that this is just the first try (really two tries, I’m giving two attempts for each outcome this week). There will be many more opportunities coming up.

  • Outcome quizzes are autograded on Canvas, but the work you do to solve the problems should be done in the Deepnote template provided.

  • “How I earned an A” token-earning assignment due at midnight tonight. Remember, this is an optional assignment. Another opportunity to earn tokens will be released for this week.

  • Homework 1 and Homework 2 are due Wednesday at midnight. Submit a token request form if you need an extension.

Question about Homework 2: There are two date-like columns. Which one should I use?

Answer: Either is fine! Depending on which one you use, the values you get might be off-by-one from what the homework says the answer should be.

Working with dates in pandas#

The content of this portion of the lecture corresponds to SLO P6.

Quick recap of last lecture#

import pandas as pd
df = pd.read_csv("taxis.csv")
df.head()
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan
  • Convert the pickup and dropoff columns to datetime values using the pandas function to_datetime. Save the results as a new column in df named “picktime” and “droptime”.

#How we can create new columns
df["picktime"] = pd.to_datetime(df["pickup"])
df["droptime"] = pd.to_datetime(df["dropoff"])
#Notice that our new columns are all the way at the end!
df
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02

6433 rows Ă— 16 columns

What’s the point of converting to datetime? These objects give us access to attributes and methods that we couldn’t use on strings.

New material#

Here’s how we can get all the methods and attributes of datetime objects available to us:

The letters dt tell pandas that we want to access datetime. This is called an accessor, and without it, we won’t have access to these methods and attributes.

It can be a little confusing to tell which are attributes and which are methods…the best thing to do is just look up what you need (or try both ways)…

dir(df["picktime"].dt)
['__annotations__',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__frozen',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_accessors',
 '_add_delegate_accessors',
 '_constructor',
 '_delegate_method',
 '_delegate_property_get',
 '_delegate_property_set',
 '_dir_additions',
 '_dir_deletions',
 '_freeze',
 '_get_values',
 '_hidden_attrs',
 '_parent',
 '_reset_cache',
 'ceil',
 'date',
 'day',
 'day_name',
 'day_of_week',
 'day_of_year',
 'dayofweek',
 'dayofyear',
 'days_in_month',
 'daysinmonth',
 'floor',
 'freq',
 'hour',
 'is_leap_year',
 'is_month_end',
 'is_month_start',
 'is_quarter_end',
 'is_quarter_start',
 'is_year_end',
 'is_year_start',
 'isocalendar',
 'microsecond',
 'minute',
 'month',
 'month_name',
 'nanosecond',
 'normalize',
 'quarter',
 'round',
 'second',
 'strftime',
 'time',
 'timetz',
 'to_period',
 'to_pydatetime',
 'tz',
 'tz_convert',
 'tz_localize',
 'week',
 'weekday',
 'weekofyear',
 'year']
  • Make a new column “day” containing the day of the week of the pickup. Use the dt accessor and then the method day_name.

df["day"] = df["picktime"].dt.day_name()
df
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday

6433 rows Ă— 17 columns

  • Make a new column “duration” which stores how long the ride took.

Because we made two columns containing date time values, we can just subtract them to get how long the taxi ride lasted. Notice, we could not do this if we had just stuck with strings.

df["duration"] = df["droptime"] - df["picktime"]
df
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday 0 days 00:06:15
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday 0 days 00:07:05
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday 0 days 00:07:24
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday 0 days 00:25:52
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday 0 days 00:09:32
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday 0 days 00:03:34
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday 0 days 00:56:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday 0 days 00:19:07
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday 0 days 00:05:04
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday 0 days 00:16:40

6433 rows Ă— 18 columns

#First three rows, first two columns
df.iloc[:3,:2]
pickup dropoff
0 2019-03-23 20:21:09 2019-03-23 20:27:24
1 2019-03-04 16:11:55 2019-03-04 16:19:00
2 2019-03-27 17:53:01 2019-03-27 18:00:25

We can see in row 0 that the person was picked up at 8:21pm and dropped off at 8:27pm. The whole trip took about 6 minutes, which is consistent with the duration that we computed above.

Working with strings in pandas#

  • How many rows in df have the word “Airport” in either the “pickup_zone” column or the “dropoff_zone” column. Do any of the rows have the word “Airport” in both columns?

    • Use the str accessor and the contains method

Test cases before we solve the problem…

df["pickup_zone"][:3]
0          Lenox Hill West
1    Upper West Side South
2            Alphabet City
Name: pickup_zone, dtype: object
df["pickup_zone"][:3].str.contains("Alphabet")
0    False
1    False
2     True
Name: pickup_zone, dtype: bool
df["pickup_zone"][:3].str.contains("City")
0    False
1    False
2     True
Name: pickup_zone, dtype: bool

We’ll extend this idea to the entire pickup_zone column. Let’s see one more example…

#Check for something that never appears
df["pickup_zone"][:3].str.contains("Gotham")
0    False
1    False
2    False
Name: pickup_zone, dtype: bool
#Check: case sensitive?
#A: yes!
df["pickup_zone"][:3].str.contains("alphabet")
0    False
1    False
2    False
Name: pickup_zone, dtype: bool
#still case sensitive
df["pickup_zone"][:3].str.contains("alphabet city")
0    False
1    False
2    False
Name: pickup_zone, dtype: bool

Let’s start by checking for all rides which involve the airport in some capacity (e.g. either start or end at an airport…or both)

We might be concerned about case sensitivity. I know this dataset and know that if Airport appears, it will be capitalized.

#Since we're dealing with pandas, we use | for "or"
bool_ser = (df["pickup_zone"].str.contains("Airport")) | (df["dropoff_zone"].str.contains("Airport"))
bool_ser
0       False
1       False
2       False
3       False
4       False
        ...  
6428    False
6429    False
6430    False
6431    False
6432    False
Length: 6433, dtype: bool

It might look like there are not places where this is True, but we are just seeing the very beginning and end of the data. How could we quickly count how many rows this is true for?

bool_ser.sum()
407

There are 297 rows where either the pickup or dropoff involved an airport.

Let’s get the sub-DataFrame with these rows.

df[bool_ser]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
10 2019-03-16 10:02:25 2019-03-16 10:22:29 1 3.90 17.00 0.00 0.00 17.80 yellow cash LaGuardia Airport Astoria Queens Queens 2019-03-16 10:02:25 2019-03-16 10:22:29 Saturday 0 days 00:20:04
22 2019-03-28 17:20:54 2019-03-28 17:55:57 1 9.82 31.50 8.31 5.76 49.87 yellow credit card LaGuardia Airport Sutton Place/Turtle Bay North Queens Manhattan 2019-03-28 17:20:54 2019-03-28 17:55:57 Thursday 0 days 00:35:03
43 2019-03-27 19:39:16 2019-03-27 20:00:26 1 9.50 28.00 0.00 5.76 35.06 yellow cash LaGuardia Airport Washington Heights South Queens Manhattan 2019-03-27 19:39:16 2019-03-27 20:00:26 Wednesday 0 days 00:21:10
53 2019-03-20 18:49:24 2019-03-20 19:12:40 1 13.45 36.00 0.00 0.00 37.80 yellow cash JFK Airport Sunnyside Queens Queens 2019-03-20 18:49:24 2019-03-20 19:12:40 Wednesday 0 days 00:23:16
56 2019-03-05 17:57:00 2019-03-05 18:45:25 2 19.59 52.00 0.00 5.76 65.56 yellow credit card JFK Airport Upper East Side North Queens Manhattan 2019-03-05 17:57:00 2019-03-05 18:45:25 Tuesday 0 days 00:48:25
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6243 2019-03-12 11:40:49 2019-03-12 11:49:23 1 3.50 12.00 0.00 0.00 12.80 green cash Steinway LaGuardia Airport Queens Queens 2019-03-12 11:40:49 2019-03-12 11:49:23 Tuesday 0 days 00:08:34
6280 2019-03-27 12:25:04 2019-03-27 12:31:15 1 2.74 10.00 0.00 0.00 10.80 green credit card Steinway LaGuardia Airport Queens Queens 2019-03-27 12:25:04 2019-03-27 12:31:15 Wednesday 0 days 00:06:11
6322 2019-03-01 17:03:11 2019-03-01 17:17:11 1 5.39 17.00 3.76 0.00 22.56 green credit card Jamaica JFK Airport Queens Queens 2019-03-01 17:03:11 2019-03-01 17:17:11 Friday 0 days 00:14:00
6396 2019-03-15 17:44:09 2019-03-15 18:20:25 1 11.44 41.63 0.00 0.00 42.13 green credit card Bushwick South LaGuardia Airport Brooklyn Queens 2019-03-15 17:44:09 2019-03-15 18:20:25 Friday 0 days 00:36:16
6398 2019-03-17 13:07:29 2019-03-17 13:51:56 1 18.39 50.50 7.70 0.00 59.00 green credit card DUMBO/Vinegar Hill JFK Airport Brooklyn Queens 2019-03-17 13:07:29 2019-03-17 13:51:56 Sunday 0 days 00:44:27

407 rows Ă— 18 columns

Now, let’s get all rides that start and end at an airport.

bool_ser2 = (df["pickup_zone"].str.contains("Airport")) & (df["dropoff_zone"].str.contains("Airport"))
bool_ser2
0       False
1       False
2       False
3       False
4       False
        ...  
6428    False
6429    False
6430    False
6431    False
6432    False
Length: 6433, dtype: bool
bool_ser2.sum()
11
df[bool_ser2]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
120 2019-03-21 17:21:44 2019-03-21 17:21:49 1 0.00 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-21 17:21:44 2019-03-21 17:21:49 Thursday 0 days 00:00:05
770 2019-03-02 03:16:59 2019-03-02 03:17:06 0 9.40 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens 2019-03-02 03:16:59 2019-03-02 03:17:06 Saturday 0 days 00:00:07
1080 2019-03-04 14:17:05 2019-03-04 14:17:13 1 0.00 2.50 0.00 0.00 3.30 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-04 14:17:05 2019-03-04 14:17:13 Monday 0 days 00:00:08
1089 2019-03-10 01:43:32 2019-03-10 01:45:22 1 0.37 3.50 0.00 0.00 4.80 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-10 01:43:32 2019-03-10 01:45:22 Sunday 0 days 00:01:50
1416 2019-03-09 13:16:32 2019-03-09 13:46:11 2 12.39 35.00 0.00 0.00 35.80 yellow cash LaGuardia Airport JFK Airport Queens Queens 2019-03-09 13:16:32 2019-03-09 13:46:11 Saturday 0 days 00:29:39
1929 2019-03-13 22:35:35 2019-03-13 22:35:49 1 0.00 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens 2019-03-13 22:35:35 2019-03-13 22:35:49 Wednesday 0 days 00:00:14
2387 2019-03-28 15:58:52 2019-03-28 15:59:25 1 1.80 69.06 20.80 0.00 90.16 yellow credit card JFK Airport JFK Airport Queens Queens 2019-03-28 15:58:52 2019-03-28 15:59:25 Thursday 0 days 00:00:33
3571 2019-03-22 16:47:41 2019-03-22 16:47:50 1 0.81 66.00 0.00 0.00 66.80 yellow credit card JFK Airport JFK Airport Queens Queens 2019-03-22 16:47:41 2019-03-22 16:47:50 Friday 0 days 00:00:09
4358 2019-03-06 18:24:00 2019-03-06 18:24:13 2 0.01 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-06 18:24:00 2019-03-06 18:24:13 Wednesday 0 days 00:00:13
5095 2019-03-30 20:14:44 2019-03-30 21:01:28 3 18.91 52.00 8.78 5.76 67.34 yellow credit card JFK Airport JFK Airport Queens Queens 2019-03-30 20:14:44 2019-03-30 21:01:28 Saturday 0 days 00:46:44
5364 2019-03-17 16:59:17 2019-03-17 18:04:08 2 36.70 150.00 0.00 24.02 174.82 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-17 16:59:17 2019-03-17 18:04:08 Sunday 0 days 01:04:51

There was an issue above where I misspelled “Airport”. Below is the code we wrote to try troubleshooting. Idea? Is it the fact that Airport is not the first word? Nope! We can check here…

df["pickup_zone"].str.contains("Airport")[120]
True

Question: Is Series.sum() faster than sum(Series). Answer: Yes! sum() is a built-in python function and has to work for a large number of data types. On the other hand, .sum() is specialized for pandas Series and runs very fast: * Series objects (like NumPy arrays) have elements all of the same data types * Vectorized operations (has a way of working with the entire series at once)

Here is a slightly more organized way of getting the same answer.

ps = df["pickup_zone"].str.contains("Airport")
ds = df["dropoff_zone"].str.contains("Airport")
#Or case
df[ps | ds]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
10 2019-03-16 10:02:25 2019-03-16 10:22:29 1 3.90 17.00 0.00 0.00 17.80 yellow cash LaGuardia Airport Astoria Queens Queens 2019-03-16 10:02:25 2019-03-16 10:22:29 Saturday 0 days 00:20:04
22 2019-03-28 17:20:54 2019-03-28 17:55:57 1 9.82 31.50 8.31 5.76 49.87 yellow credit card LaGuardia Airport Sutton Place/Turtle Bay North Queens Manhattan 2019-03-28 17:20:54 2019-03-28 17:55:57 Thursday 0 days 00:35:03
43 2019-03-27 19:39:16 2019-03-27 20:00:26 1 9.50 28.00 0.00 5.76 35.06 yellow cash LaGuardia Airport Washington Heights South Queens Manhattan 2019-03-27 19:39:16 2019-03-27 20:00:26 Wednesday 0 days 00:21:10
53 2019-03-20 18:49:24 2019-03-20 19:12:40 1 13.45 36.00 0.00 0.00 37.80 yellow cash JFK Airport Sunnyside Queens Queens 2019-03-20 18:49:24 2019-03-20 19:12:40 Wednesday 0 days 00:23:16
56 2019-03-05 17:57:00 2019-03-05 18:45:25 2 19.59 52.00 0.00 5.76 65.56 yellow credit card JFK Airport Upper East Side North Queens Manhattan 2019-03-05 17:57:00 2019-03-05 18:45:25 Tuesday 0 days 00:48:25
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6243 2019-03-12 11:40:49 2019-03-12 11:49:23 1 3.50 12.00 0.00 0.00 12.80 green cash Steinway LaGuardia Airport Queens Queens 2019-03-12 11:40:49 2019-03-12 11:49:23 Tuesday 0 days 00:08:34
6280 2019-03-27 12:25:04 2019-03-27 12:31:15 1 2.74 10.00 0.00 0.00 10.80 green credit card Steinway LaGuardia Airport Queens Queens 2019-03-27 12:25:04 2019-03-27 12:31:15 Wednesday 0 days 00:06:11
6322 2019-03-01 17:03:11 2019-03-01 17:17:11 1 5.39 17.00 3.76 0.00 22.56 green credit card Jamaica JFK Airport Queens Queens 2019-03-01 17:03:11 2019-03-01 17:17:11 Friday 0 days 00:14:00
6396 2019-03-15 17:44:09 2019-03-15 18:20:25 1 11.44 41.63 0.00 0.00 42.13 green credit card Bushwick South LaGuardia Airport Brooklyn Queens 2019-03-15 17:44:09 2019-03-15 18:20:25 Friday 0 days 00:36:16
6398 2019-03-17 13:07:29 2019-03-17 13:51:56 1 18.39 50.50 7.70 0.00 59.00 green credit card DUMBO/Vinegar Hill JFK Airport Brooklyn Queens 2019-03-17 13:07:29 2019-03-17 13:51:56 Sunday 0 days 00:44:27

407 rows Ă— 18 columns

#And case
df[ps & ds]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
120 2019-03-21 17:21:44 2019-03-21 17:21:49 1 0.00 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-21 17:21:44 2019-03-21 17:21:49 Thursday 0 days 00:00:05
770 2019-03-02 03:16:59 2019-03-02 03:17:06 0 9.40 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens 2019-03-02 03:16:59 2019-03-02 03:17:06 Saturday 0 days 00:00:07
1080 2019-03-04 14:17:05 2019-03-04 14:17:13 1 0.00 2.50 0.00 0.00 3.30 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-04 14:17:05 2019-03-04 14:17:13 Monday 0 days 00:00:08
1089 2019-03-10 01:43:32 2019-03-10 01:45:22 1 0.37 3.50 0.00 0.00 4.80 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-10 01:43:32 2019-03-10 01:45:22 Sunday 0 days 00:01:50
1416 2019-03-09 13:16:32 2019-03-09 13:46:11 2 12.39 35.00 0.00 0.00 35.80 yellow cash LaGuardia Airport JFK Airport Queens Queens 2019-03-09 13:16:32 2019-03-09 13:46:11 Saturday 0 days 00:29:39
1929 2019-03-13 22:35:35 2019-03-13 22:35:49 1 0.00 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens 2019-03-13 22:35:35 2019-03-13 22:35:49 Wednesday 0 days 00:00:14
2387 2019-03-28 15:58:52 2019-03-28 15:59:25 1 1.80 69.06 20.80 0.00 90.16 yellow credit card JFK Airport JFK Airport Queens Queens 2019-03-28 15:58:52 2019-03-28 15:59:25 Thursday 0 days 00:00:33
3571 2019-03-22 16:47:41 2019-03-22 16:47:50 1 0.81 66.00 0.00 0.00 66.80 yellow credit card JFK Airport JFK Airport Queens Queens 2019-03-22 16:47:41 2019-03-22 16:47:50 Friday 0 days 00:00:09
4358 2019-03-06 18:24:00 2019-03-06 18:24:13 2 0.01 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-06 18:24:00 2019-03-06 18:24:13 Wednesday 0 days 00:00:13
5095 2019-03-30 20:14:44 2019-03-30 21:01:28 3 18.91 52.00 8.78 5.76 67.34 yellow credit card JFK Airport JFK Airport Queens Queens 2019-03-30 20:14:44 2019-03-30 21:01:28 Saturday 0 days 00:46:44
5364 2019-03-17 16:59:17 2019-03-17 18:04:08 2 36.70 150.00 0.00 24.02 174.82 yellow cash JFK Airport JFK Airport Queens Queens 2019-03-17 16:59:17 2019-03-17 18:04:08 Sunday 0 days 01:04:51

Working with missing values in pandas#

Two main options for dealing with missing data:

  • Ignore it! Drop the rows that have at least one missing value (Mostly what we’ll do in Math 10).

  • Interpolate using known rows to put a good “guess” for the missing value (not something we’ll do in Math 10)

df
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday 0 days 00:06:15
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday 0 days 00:07:05
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday 0 days 00:07:24
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday 0 days 00:25:52
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday 0 days 00:09:32
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday 0 days 00:03:34
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday 0 days 00:56:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday 0 days 00:19:07
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday 0 days 00:05:04
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday 0 days 00:16:40

6433 rows Ă— 18 columns

  • Look at df.info again. Which rows have missing values?

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6433 entries, 0 to 6432
Data columns (total 18 columns):
 #   Column           Non-Null Count  Dtype          
---  ------           --------------  -----          
 0   pickup           6433 non-null   object         
 1   dropoff          6433 non-null   object         
 2   passengers       6433 non-null   int64          
 3   distance         6433 non-null   float64        
 4   fare             6433 non-null   float64        
 5   tip              6433 non-null   float64        
 6   tolls            6433 non-null   float64        
 7   total            6433 non-null   float64        
 8   color            6433 non-null   object         
 9   payment          6389 non-null   object         
 10  pickup_zone      6407 non-null   object         
 11  dropoff_zone     6388 non-null   object         
 12  pickup_borough   6407 non-null   object         
 13  dropoff_borough  6388 non-null   object         
 14  picktime         6433 non-null   datetime64[ns] 
 15  droptime         6433 non-null   datetime64[ns] 
 16  day              6433 non-null   object         
 17  duration         6433 non-null   timedelta64[ns]
dtypes: datetime64[ns](2), float64(5), int64(1), object(9), timedelta64[ns](1)
memory usage: 904.8+ KB
#Count how many values are missing from the payment column?
6433 - 6389
44

Here’s a slightly nicer way:

df["payment"].isna().sum()
44

A common task is to remove all the rows which are missing any values.

Here’s the easiest way:

Notice, the code below does not actually change df. It just displays what df looks like with missing values. If I actually wanted to change df I’d need to include df =...

#Notice row label 7 is missing!
df.dropna()
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday 0 days 00:06:15
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday 0 days 00:07:05
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday 0 days 00:07:24
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday 0 days 00:25:52
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday 0 days 00:09:32
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday 0 days 00:03:34
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday 0 days 00:56:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday 0 days 00:19:07
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday 0 days 00:05:04
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday 0 days 00:16:40

6341 rows Ă— 18 columns

Question: How could we remove a column with a missing value? Answer: dropna() takes an axis keyword

help(df.dropna)
Help on method dropna in module pandas.core.frame:

dropna(axis: 'Axis' = 0, how: 'str' = 'any', thresh=None, subset: 'IndexLabel' = None, inplace: 'bool' = False) method of pandas.core.frame.DataFrame instance
    Remove missing values.
    
    See the :ref:`User Guide <missing_data>` for more on which values are
    considered missing, and how to work with missing data.
    
    Parameters
    ----------
    axis : {0 or 'index', 1 or 'columns'}, default 0
        Determine if rows or columns which contain missing values are
        removed.
    
        * 0, or 'index' : Drop rows which contain missing values.
        * 1, or 'columns' : Drop columns which contain missing value.
    
        .. versionchanged:: 1.0.0
    
           Pass tuple or list to drop on multiple axes.
           Only a single axis is allowed.
    
    how : {'any', 'all'}, default 'any'
        Determine if row or column is removed from DataFrame, when we have
        at least one NA or all NA.
    
        * 'any' : If any NA values are present, drop that row or column.
        * 'all' : If all values are NA, drop that row or column.
    
    thresh : int, optional
        Require that many non-NA values.
    subset : column label or sequence of labels, optional
        Labels along other axis to consider, e.g. if you are dropping rows
        these would be a list of columns to include.
    inplace : bool, default False
        If True, do operation inplace and return None.
    
    Returns
    -------
    DataFrame or None
        DataFrame with NA entries dropped from it or None if ``inplace=True``.
    
    See Also
    --------
    DataFrame.isna: Indicate missing values.
    DataFrame.notna : Indicate existing (non-missing) values.
    DataFrame.fillna : Replace missing values.
    Series.dropna : Drop missing values.
    Index.dropna : Drop missing indices.
    
    Examples
    --------
    >>> df = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
    ...                    "toy": [np.nan, 'Batmobile', 'Bullwhip'],
    ...                    "born": [pd.NaT, pd.Timestamp("1940-04-25"),
    ...                             pd.NaT]})
    >>> df
           name        toy       born
    0    Alfred        NaN        NaT
    1    Batman  Batmobile 1940-04-25
    2  Catwoman   Bullwhip        NaT
    
    Drop the rows where at least one element is missing.
    
    >>> df.dropna()
         name        toy       born
    1  Batman  Batmobile 1940-04-25
    
    Drop the columns where at least one element is missing.
    
    >>> df.dropna(axis='columns')
           name
    0    Alfred
    1    Batman
    2  Catwoman
    
    Drop the rows where all elements are missing.
    
    >>> df.dropna(how='all')
           name        toy       born
    0    Alfred        NaN        NaT
    1    Batman  Batmobile 1940-04-25
    2  Catwoman   Bullwhip        NaT
    
    Keep only the rows with at least 2 non-NA values.
    
    >>> df.dropna(thresh=2)
           name        toy       born
    1    Batman  Batmobile 1940-04-25
    2  Catwoman   Bullwhip        NaT
    
    Define in which columns to look for missing values.
    
    >>> df.dropna(subset=['name', 'toy'])
           name        toy       born
    1    Batman  Batmobile 1940-04-25
    2  Catwoman   Bullwhip        NaT
    
    Keep the DataFrame with valid entries in the same variable.
    
    >>> df.dropna(inplace=True)
    >>> df
         name        toy       born
    1  Batman  Batmobile 1940-04-25
#Should remove all columns with at least one missing value
#As a sanity check, compare with df.info()
df.dropna(axis=1)
pickup dropoff passengers distance fare tip tolls total color picktime droptime day duration
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday 0 days 00:06:15
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday 0 days 00:07:05
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday 0 days 00:07:24
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday 0 days 00:25:52
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday 0 days 00:09:32
... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday 0 days 00:03:34
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday 0 days 00:56:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday 0 days 00:19:07
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday 0 days 00:05:04
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday 0 days 00:16:40

6433 rows Ă— 13 columns

Here’s how we can remove missing rows without using dropna. This is just for practice with any and all…

df
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday 0 days 00:06:15
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday 0 days 00:07:05
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday 0 days 00:07:24
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday 0 days 00:25:52
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday 0 days 00:09:32
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday 0 days 00:03:34
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday 0 days 00:56:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday 0 days 00:19:07
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday 0 days 00:05:04
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday 0 days 00:16:40

6433 rows Ă— 18 columns

df.isna().any(axis=1)
0       False
1       False
2       False
3       False
4       False
        ...  
6428    False
6429    False
6430    False
6431    False
6432    False
Length: 6433, dtype: bool
#All of the rows which have at least one missing value
df[df.isna().any(axis=1)]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
7 2019-03-22 12:47:13 2019-03-22 12:58:17 0 1.4 8.5 0.00 0.0 11.80 yellow NaN Murray Hill Flatiron Manhattan Manhattan 2019-03-22 12:47:13 2019-03-22 12:58:17 Friday 0 days 00:11:04
42 2019-03-30 23:59:14 2019-03-30 23:59:17 1 0.0 80.0 20.08 0.0 100.38 yellow credit card NaN NaN NaN NaN 2019-03-30 23:59:14 2019-03-30 23:59:17 Saturday 0 days 00:00:03
445 2019-03-19 06:57:14 2019-03-19 07:00:08 1 1.3 5.5 0.00 0.0 6.30 yellow NaN Boerum Hill Columbia Street Brooklyn Brooklyn 2019-03-19 06:57:14 2019-03-19 07:00:08 Tuesday 0 days 00:02:54
491 2019-03-07 07:11:33 2019-03-07 07:11:39 1 1.6 2.5 0.00 0.0 5.80 yellow NaN Murray Hill Murray Hill Manhattan Manhattan 2019-03-07 07:11:33 2019-03-07 07:11:39 Thursday 0 days 00:00:06
545 2019-03-27 11:03:43 2019-03-27 11:14:34 1 4.2 15.0 0.00 0.0 15.80 yellow NaN LaGuardia Airport Forest Hills Queens Queens 2019-03-27 11:03:43 2019-03-27 11:14:34 Wednesday 0 days 00:10:51
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6118 2019-03-30 00:49:48 2019-03-30 00:49:56 1 0.0 25.0 0.00 0.0 25.50 green credit card Prospect Heights NaN Brooklyn NaN 2019-03-30 00:49:48 2019-03-30 00:49:56 Saturday 0 days 00:00:08
6169 2019-03-27 02:11:01 2019-03-27 02:12:03 1 4.1 3.0 0.00 0.0 4.30 green NaN Jackson Heights Jackson Heights Queens Queens 2019-03-27 02:11:01 2019-03-27 02:12:03 Wednesday 0 days 00:01:02
6311 2019-03-12 07:10:30 2019-03-12 07:14:18 1 0.7 4.5 0.00 0.0 5.30 green NaN Long Island City/Hunters Point Long Island City/Hunters Point Queens Queens 2019-03-12 07:10:30 2019-03-12 07:14:18 Tuesday 0 days 00:03:48
6314 2019-03-28 22:36:04 2019-03-28 22:36:07 1 0.0 25.0 0.00 0.0 25.00 green cash Jamaica NaN Queens NaN 2019-03-28 22:36:04 2019-03-28 22:36:07 Thursday 0 days 00:00:03
6356 2019-03-01 16:58:23 2019-03-01 16:58:23 1 0.0 3.0 0.00 0.0 4.80 green cash Stuyvesant Heights NaN Brooklyn NaN 2019-03-01 16:58:23 2019-03-01 16:58:23 Friday 0 days 00:00:00

92 rows Ă— 18 columns

#Keep all rows that have no missing values
df[~df.isna().any(axis=1)]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
0 2019-03-23 20:21:09 2019-03-23 20:27:24 1 1.60 7.0 2.15 0.0 12.95 yellow credit card Lenox Hill West UN/Turtle Bay South Manhattan Manhattan 2019-03-23 20:21:09 2019-03-23 20:27:24 Saturday 0 days 00:06:15
1 2019-03-04 16:11:55 2019-03-04 16:19:00 1 0.79 5.0 0.00 0.0 9.30 yellow cash Upper West Side South Upper West Side South Manhattan Manhattan 2019-03-04 16:11:55 2019-03-04 16:19:00 Monday 0 days 00:07:05
2 2019-03-27 17:53:01 2019-03-27 18:00:25 1 1.37 7.5 2.36 0.0 14.16 yellow credit card Alphabet City West Village Manhattan Manhattan 2019-03-27 17:53:01 2019-03-27 18:00:25 Wednesday 0 days 00:07:24
3 2019-03-10 01:23:59 2019-03-10 01:49:51 1 7.70 27.0 6.15 0.0 36.95 yellow credit card Hudson Sq Yorkville West Manhattan Manhattan 2019-03-10 01:23:59 2019-03-10 01:49:51 Sunday 0 days 00:25:52
4 2019-03-30 13:27:42 2019-03-30 13:37:14 3 2.16 9.0 1.10 0.0 13.40 yellow credit card Midtown East Yorkville West Manhattan Manhattan 2019-03-30 13:27:42 2019-03-30 13:37:14 Saturday 0 days 00:09:32
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
6428 2019-03-31 09:51:53 2019-03-31 09:55:27 1 0.75 4.5 1.06 0.0 6.36 green credit card East Harlem North Central Harlem North Manhattan Manhattan 2019-03-31 09:51:53 2019-03-31 09:55:27 Sunday 0 days 00:03:34
6429 2019-03-31 17:38:00 2019-03-31 18:34:23 1 18.74 58.0 0.00 0.0 58.80 green credit card Jamaica East Concourse/Concourse Village Queens Bronx 2019-03-31 17:38:00 2019-03-31 18:34:23 Sunday 0 days 00:56:23
6430 2019-03-23 22:55:18 2019-03-23 23:14:25 1 4.14 16.0 0.00 0.0 17.30 green cash Crown Heights North Bushwick North Brooklyn Brooklyn 2019-03-23 22:55:18 2019-03-23 23:14:25 Saturday 0 days 00:19:07
6431 2019-03-04 10:09:25 2019-03-04 10:14:29 1 1.12 6.0 0.00 0.0 6.80 green credit card East New York East Flatbush/Remsen Village Brooklyn Brooklyn 2019-03-04 10:09:25 2019-03-04 10:14:29 Monday 0 days 00:05:04
6432 2019-03-13 19:31:22 2019-03-13 19:48:02 1 3.85 15.0 3.36 0.0 20.16 green credit card Boerum Hill Windsor Terrace Brooklyn Brooklyn 2019-03-13 19:31:22 2019-03-13 19:48:02 Wednesday 0 days 00:16:40

6341 rows Ă— 18 columns

  • Define df_sub to be the sub-DataFrame containing all the rows for which the “pickup_zone” entry is missing. Use the isna method.

#series where pickup_zone is missing
bool_ser = df["pickup_zone"].isna()
bool_ser
0       False
1       False
2       False
3       False
4       False
        ...  
6428    False
6429    False
6430    False
6431    False
6432    False
Name: pickup_zone, Length: 6433, dtype: bool
#Sanity check: every entry in pickup_zone should be missing
df[bool_ser]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough picktime droptime day duration
42 2019-03-30 23:59:14 2019-03-30 23:59:17 1 0.00 80.0 20.08 0.00 100.38 yellow credit card NaN NaN NaN NaN 2019-03-30 23:59:14 2019-03-30 23:59:17 Saturday 0 days 00:00:03
606 2019-03-19 15:04:40 2019-03-19 15:06:15 1 0.40 3.5 1.35 0.00 8.15 yellow credit card NaN Upper East Side South NaN Manhattan 2019-03-19 15:04:40 2019-03-19 15:06:15 Tuesday 0 days 00:01:35
622 2019-03-12 19:52:36 2019-03-12 19:52:55 3 0.00 120.0 33.20 12.50 166.00 yellow credit card NaN NaN NaN NaN 2019-03-12 19:52:36 2019-03-12 19:52:55 Tuesday 0 days 00:00:19
671 2019-03-09 22:45:46 2019-03-09 22:46:50 1 0.40 3.5 0.00 0.00 7.30 yellow cash NaN Lincoln Square East NaN Manhattan 2019-03-09 22:45:46 2019-03-09 22:46:50 Saturday 0 days 00:01:04
712 2019-03-03 01:24:45 2019-03-03 01:29:32 1 0.80 5.0 1.75 0.00 10.55 yellow credit card NaN West Chelsea/Hudson Yards NaN Manhattan 2019-03-03 01:24:45 2019-03-03 01:29:32 Sunday 0 days 00:04:47
970 2019-03-29 00:02:00 2019-03-29 00:02:05 2 0.00 45.0 5.00 0.00 50.30 yellow credit card NaN NaN NaN NaN 2019-03-29 00:02:00 2019-03-29 00:02:05 Friday 0 days 00:00:05
1108 2019-03-10 09:33:13 2019-03-10 09:52:04 1 13.40 52.0 11.70 5.76 70.26 yellow credit card NaN NaN NaN NaN 2019-03-10 09:33:13 2019-03-10 09:52:04 Sunday 0 days 00:18:51
1961 2019-03-19 16:43:59 2019-03-19 17:37:22 1 17.82 52.0 13.11 5.76 78.67 yellow credit card NaN Garment District NaN Manhattan 2019-03-19 16:43:59 2019-03-19 17:37:22 Tuesday 0 days 00:53:23
2137 2019-03-08 13:27:32 2019-03-08 13:46:23 1 1.40 12.0 3.05 0.00 18.35 yellow credit card NaN NaN NaN NaN 2019-03-08 13:27:32 2019-03-08 13:46:23 Friday 0 days 00:18:51
2742 2019-03-23 06:20:27 2019-03-23 06:20:59 1 0.00 55.0 0.00 0.00 55.80 yellow credit card NaN NaN NaN NaN 2019-03-23 06:20:27 2019-03-23 06:20:59 Saturday 0 days 00:00:32
3085 2019-03-24 15:43:02 2019-03-24 16:02:57 1 3.20 14.5 0.00 0.00 15.30 yellow cash NaN NaN NaN NaN 2019-03-24 15:43:02 2019-03-24 16:02:57 Sunday 0 days 00:19:55
3259 2019-03-30 00:39:09 2019-03-30 00:43:34 1 0.84 5.0 1.70 0.00 10.50 yellow credit card NaN NaN NaN NaN 2019-03-30 00:39:09 2019-03-30 00:43:34 Saturday 0 days 00:04:25
3644 2019-03-19 23:30:50 2019-03-19 23:32:33 2 0.00 103.0 20.65 0.00 123.95 yellow credit card NaN NaN NaN NaN 2019-03-19 23:30:50 2019-03-19 23:32:33 Tuesday 0 days 00:01:43
3793 2019-03-24 06:07:30 2019-03-24 06:12:22 1 1.50 6.5 0.00 0.00 9.80 yellow NaN NaN Midtown East NaN Manhattan 2019-03-24 06:07:30 2019-03-24 06:12:22 Sunday 0 days 00:04:52
3889 2019-03-30 06:42:55 2019-03-30 06:43:00 1 0.00 2.5 0.00 0.00 3.30 yellow cash NaN NaN NaN NaN 2019-03-30 06:42:55 2019-03-30 06:43:00 Saturday 0 days 00:00:05
4118 2019-03-15 14:01:54 2019-03-15 14:01:59 1 0.00 25.0 5.06 0.00 30.36 yellow credit card NaN NaN NaN NaN 2019-03-15 14:01:54 2019-03-15 14:01:59 Friday 0 days 00:00:05
4127 2019-03-01 05:18:21 2019-03-01 05:18:30 2 0.04 2.5 0.00 0.00 3.80 yellow cash NaN NaN NaN NaN 2019-03-01 05:18:21 2019-03-01 05:18:30 Friday 0 days 00:00:09
4281 2019-03-18 23:29:49 2019-03-18 23:38:00 1 2.10 9.0 2.06 0.00 12.36 yellow credit card NaN NaN NaN NaN 2019-03-18 23:29:49 2019-03-18 23:38:00 Monday 0 days 00:08:11
4414 2019-03-29 20:42:47 2019-03-29 21:03:50 1 4.20 17.0 4.80 5.76 28.86 yellow credit card NaN NaN NaN NaN 2019-03-29 20:42:47 2019-03-29 21:03:50 Friday 0 days 00:21:03
4772 2019-03-21 19:51:13 2019-03-21 19:57:03 1 0.72 5.5 1.46 0.00 8.76 yellow credit card NaN NaN NaN NaN 2019-03-21 19:51:13 2019-03-21 19:57:03 Thursday 0 days 00:05:50
4941 2019-03-01 08:12:28 2019-03-01 08:17:19 1 0.83 5.0 2.50 0.00 10.80 yellow credit card NaN NaN NaN NaN 2019-03-01 08:12:28 2019-03-01 08:17:19 Friday 0 days 00:04:51
5263 2019-03-09 20:37:53 2019-03-09 21:07:20 1 4.99 22.0 5.16 0.00 30.96 yellow credit card NaN NaN NaN NaN 2019-03-09 20:37:53 2019-03-09 21:07:20 Saturday 0 days 00:29:27
5493 2019-03-06 12:14:00 2019-03-06 12:14:00 1 0.00 10.0 0.00 0.00 10.00 green credit card NaN NaN NaN NaN 2019-03-06 12:14:00 2019-03-06 12:14:00 Wednesday 0 days 00:00:00
5624 2019-03-11 14:04:50 2019-03-11 14:04:50 1 0.00 2.5 0.00 0.00 3.30 green cash NaN NaN NaN NaN 2019-03-11 14:04:50 2019-03-11 14:04:50 Monday 0 days 00:00:00
5638 2019-03-13 12:22:00 2019-03-13 12:22:00 1 0.00 10.0 0.00 0.00 10.00 green credit card NaN NaN NaN NaN 2019-03-13 12:22:00 2019-03-13 12:22:00 Wednesday 0 days 00:00:00
6083 2019-03-19 15:34:00 2019-03-19 15:34:00 1 0.00 5.0 0.00 0.00 5.00 green credit card NaN NaN NaN NaN 2019-03-19 15:34:00 2019-03-19 15:34:00 Tuesday 0 days 00:00:00

More on missing values#

I want to show you a little bit of a more extreme case here. In the taxis data, pandas knew how to recognize the missing values. This will not always be the case!

df2 = pd.read_csv("sampleData.csv")
df2
A B C
0 3 -2.3 -1
1 2.1 1.0 0
2 ? 5.0 ?
3 12.3 -4.0 4.1
4 7 2.8 3
5 5 6.0 ?
6 ? 1.0 1.8
7 2 -1.0 3.14

The idea here is that the question marks represent missing data, but pandas doesn’t know that! This is going to cause some very big issues. Let’s see some examples.

Looking at df2, pandas thinks that “A” and “B” represent string data…this comes from the fact that quesiton marks are in these columns.

df2["A"].sum()
'32.1?12.375?2'

This is an example of string concatenation. It takes strings and puts them together.

"15" + "16"
'1516'

Because pandas does not recognize “A” and “C” as numeric columns, we also lose information from describe()

df2.describe()
B
count 8.000000
mean 1.062500
std 3.466137
min -4.000000
25% -1.325000
50% 1.000000
75% 3.350000
max 6.000000

Missing values are often handled automatically by pandas, but here’s how we can do it by hand, as we would need to in this case:

In this example, no rows are removed. We just replace all “?” with nan

df3 = pd.read_csv("sampleData.csv",na_values="?")
df3
A B C
0 3.0 -2.3 -1.00
1 2.1 1.0 0.00
2 NaN 5.0 NaN
3 12.3 -4.0 4.10
4 7.0 2.8 3.00
5 5.0 6.0 NaN
6 NaN 1.0 1.80
7 2.0 -1.0 3.14
df2
A B C
0 3 -2.3 -1
1 2.1 1.0 0
2 ? 5.0 ?
3 12.3 -4.0 4.1
4 7 2.8 3
5 5 6.0 ?
6 ? 1.0 1.8
7 2 -1.0 3.14

Notice! “A” and “C” are now recognized as columns with floating point numbers! .sum() and .describe() would work how we expect now.

How could I access the value nan directly?

By itself, I’ll get an error

nan
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [48], in <cell line: 1>()
----> 1 nan

NameError: name 'nan' is not defined
import numpy as np
np.nan
nan

Warning: We never want to check for equality with np.nan

df3.loc[2,"A"] == np.nan
False
np.nan == np.nan
False
df3["A"].isna()
0    False
1    False
2     True
3    False
4    False
5    False
6     True
7    False
Name: A, dtype: bool
type(np.nan)
float

Takeaway: Sometimes when you get errors involving floats, it’s really an error about missing values.

Getting integer locations of columns#

You might recall from an earlier part of lecture I wanted the integer-position of the “pickup_borough” column.

taxis = pd.read_csv("taxis.csv")
taxis.columns
Index(['pickup', 'dropoff', 'passengers', 'distance', 'fare', 'tip', 'tolls',
       'total', 'color', 'payment', 'pickup_zone', 'dropoff_zone',
       'pickup_borough', 'dropoff_borough'],
      dtype='object')

Then, all I did was count from 0 to the pickup_borough column. You can imagine if I had hundreds of columns this method would be very sad :(

  • Use index method of a list object

#This data type is not so important for Math 10
type(taxis.columns)
pandas.core.indexes.base.Index
mylist = list(taxis.columns)
mylist
['pickup',
 'dropoff',
 'passengers',
 'distance',
 'fare',
 'tip',
 'tolls',
 'total',
 'color',
 'payment',
 'pickup_zone',
 'dropoff_zone',
 'pickup_borough',
 'dropoff_borough']
type(mylist)
list
mylist.index("pickup_borough")
12
  • Get a boolean array and then use np.nonzero

taxis.columns == "pickup_borough"
array([False, False, False, False, False, False, False, False, False,
       False, False, False,  True, False])
#This returns a tuple
np.nonzero(taxis.columns == "pickup_borough")
(array([12]),)
np.nonzero(taxis.columns == "pickup_borough")[0]
array([12])
np.nonzero(taxis.columns == "pickup_borough")[0][0]
12
np.where(taxis.columns == "pickup_borough")
(array([12]),)
np.where(taxis.columns == "pickup_borough","Yasmeen","Anthony")
array(['Anthony', 'Anthony', 'Anthony', 'Anthony', 'Anthony', 'Anthony',
       'Anthony', 'Anthony', 'Anthony', 'Anthony', 'Anthony', 'Anthony',
       'Yasmeen', 'Anthony'], dtype='<U7')

This is where we got to in the lecture. To keep on schedule, I’ll have Anthony go over this remaining material in discussion on Wednesday.

  • Use the get_loc method of a pandas Index object (credit: Bing chat)

df.columns.get_loc("pickup_borough")
12
  • Use the get_indexer method of a pandas Index object (credit: Bing chat)

This method is very similar to get_loc, but has the additional functionality of being able to get the indices of multiple columns at once. If we wanted to do this with the other methods, it would be a lot more complicated and difficult.

df.columns.get_indexer(["pickup_borough","dropoff_zone"])
array([12, 11])

Shuffling and sampling data#

In the next section of the notes, I want to still use the taxis data, but have the rows shuffled so that the row labels don’t necessarily match their integer positions.

df = pd.read_csv("taxis.csv")
df = df.sample(frac = 0.1, random_state=10)

In the above code frac tells us what portion of the data to keep. In this case, we keep 10%. The argument random_state is functionally very similar to seeded random numbers in NumPy. It’s what allows us to get reproducible results. The df that results on your end should be the same as what’s displayed here.

df.head()
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
890 2019-03-09 16:32:40 2019-03-09 16:49:32 2 2.70 13.0 0.00 0.0 16.30 yellow cash Midtown North Kips Bay Manhattan Manhattan
5870 2019-03-26 11:04:06 2019-03-26 11:09:23 1 0.64 5.5 1.26 0.0 7.56 green credit card Morningside Heights Manhattanville Manhattan Manhattan
686 2019-03-27 15:02:00 2019-03-27 15:31:19 1 3.79 20.0 0.00 0.0 23.30 yellow cash East Chelsea Manhattan Valley Manhattan Manhattan
4937 2019-03-02 19:50:23 2019-03-02 20:04:19 2 1.60 10.0 2.75 0.0 16.55 yellow credit card TriBeCa/Civic Center East Village Manhattan Manhattan
2659 2019-03-18 21:36:06 2019-03-18 21:48:31 1 1.10 8.0 0.00 0.0 11.80 yellow cash Midtown North Midtown North Manhattan Manhattan

Notice that rows in integer positions 0,1, and 2 correspond to labels 890,5870, and 686.

I know that the original DataFrame has 6433 rows. Let’s check and see if we really got 10% of the rows.

df.shape
(643, 14)

This looks good! We have 10% of the rows.

For the next portion of the notes, I want to keep the full dataset, just with the rows shuffled. I’ll specify a frac=1, in this case.

df = pd.read_csv("taxis.csv")
df = df.sample(frac=1,random_state=10)

Checking the shape, we see that we really do have the entire dataset.

df.shape
(6433, 14)

Strings in pandas revisited: Worse approach 1 (iloc and for-loops)#

Question from earlier in the lecture:

  • How many rows in df have the word “Airport” in either the “pickup_zone” column or the “dropoff_zone” column. Do any of the rows have the word “Airport” in both columns?

The solution that we wrote together earlier really is one of the best ways I know how to solve this problem. The point of this section of the notes is to get some practice with indexing and for-loops.

len(df)
6433

The logic of the following attemp is good, but we’ll run into an error…

good_inds = []

#there's almost always a better way of iterating
#than range(len(...))
for i in range(len(df)):
    if ("Airport" in df.iloc[i,10]) and ("Airport" in df.iloc[i,11]):
        good_inds.append(i)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [75], in <cell line: 5>()
      3 #there's almost always a better way of iterating
      4 #than range(len(...))
      5 for i in range(len(df)):
----> 6     if ("Airport" in df.iloc[i,10]) and ("Airport" in df.iloc[i,11]):
      7         good_inds.append(i)

TypeError: argument of type 'float' is not iterable

Would you believe that this is an issue with missing values? Hint: What’s the datatype of np.nan?

#does this example convince you?
"Airport" in np.nan
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [76], in <cell line: 2>()
      1 #does this example convince you?
----> 2 "Airport" in np.nan

TypeError: argument of type 'float' is not iterable

The way we can get around this is by using a “try-except” block:

good_inds = []

#there's almost always a better way of iterating
#than range(len(...))
for i in range(len(df)):
    try:
        if ("Airport" in df.iloc[i,10]) and ("Airport" in df.iloc[i,11]):
            good_inds.append(i)
    except TypeError:
        #go to the next step of the for-loop without breaking
        continue
good_inds
[517, 642, 1117, 1239, 1461, 2032, 3576, 3971, 4970, 5417, 5773]
df.iloc[good_inds]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
2387 2019-03-28 15:58:52 2019-03-28 15:59:25 1 1.80 69.06 20.80 0.00 90.16 yellow credit card JFK Airport JFK Airport Queens Queens
1080 2019-03-04 14:17:05 2019-03-04 14:17:13 1 0.00 2.50 0.00 0.00 3.30 yellow cash JFK Airport JFK Airport Queens Queens
120 2019-03-21 17:21:44 2019-03-21 17:21:49 1 0.00 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens
5364 2019-03-17 16:59:17 2019-03-17 18:04:08 2 36.70 150.00 0.00 24.02 174.82 yellow cash JFK Airport JFK Airport Queens Queens
1929 2019-03-13 22:35:35 2019-03-13 22:35:49 1 0.00 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens
3571 2019-03-22 16:47:41 2019-03-22 16:47:50 1 0.81 66.00 0.00 0.00 66.80 yellow credit card JFK Airport JFK Airport Queens Queens
1416 2019-03-09 13:16:32 2019-03-09 13:46:11 2 12.39 35.00 0.00 0.00 35.80 yellow cash LaGuardia Airport JFK Airport Queens Queens
4358 2019-03-06 18:24:00 2019-03-06 18:24:13 2 0.01 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens
1089 2019-03-10 01:43:32 2019-03-10 01:45:22 1 0.37 3.50 0.00 0.00 4.80 yellow cash JFK Airport JFK Airport Queens Queens
5095 2019-03-30 20:14:44 2019-03-30 21:01:28 3 18.91 52.00 8.78 5.76 67.34 yellow credit card JFK Airport JFK Airport Queens Queens
770 2019-03-02 03:16:59 2019-03-02 03:17:06 0 9.40 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens
#this gives an error because pandas is looking for columns with these names
df[good_inds]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [80], in <cell line: 2>()
      1 #this gives an error because pandas is looking for columns with these names
----> 2 df[good_inds]

File ~/opt/miniconda3/envs/math9/lib/python3.9/site-packages/pandas/core/frame.py:3511, in DataFrame.__getitem__(self, key)
   3509     if is_iterator(key):
   3510         key = list(key)
-> 3511     indexer = self.columns._get_indexer_strict(key, "columns")[1]
   3513 # take() does not accept boolean indexers
   3514 if getattr(indexer, "dtype", None) == bool:

File ~/opt/miniconda3/envs/math9/lib/python3.9/site-packages/pandas/core/indexes/base.py:5796, in Index._get_indexer_strict(self, key, axis_name)
   5793 else:
   5794     keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr)
-> 5796 self._raise_if_missing(keyarr, indexer, axis_name)
   5798 keyarr = self.take(indexer)
   5799 if isinstance(key, Index):
   5800     # GH 42790 - Preserve name from an Index

File ~/opt/miniconda3/envs/math9/lib/python3.9/site-packages/pandas/core/indexes/base.py:5856, in Index._raise_if_missing(self, key, indexer, axis_name)
   5854     if use_interval_msg:
   5855         key = list(key)
-> 5856     raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   5858 not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())
   5859 raise KeyError(f"{not_found} not in index")

KeyError: "None of [Int64Index([517, 642, 1117, 1239, 1461, 2032, 3576, 3971, 4970, 5417, 5773], dtype='int64')] are in the [columns]"

Strings in pandas revisited: Worse approach 2 (loc and for-loops)#

In this section of the notes, we’ll be solving the same problem as before, but now in a slightly different way.

This method will require that we check that no indices are repeated in df. This typically is already true, but it’s not a requirement of DataFrames.

#attribute that holds the LHS #s
df.index[:5]
Int64Index([890, 5870, 686, 4937, 2659], dtype='int64')
df.head()
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
890 2019-03-09 16:32:40 2019-03-09 16:49:32 2 2.70 13.0 0.00 0.0 16.30 yellow cash Midtown North Kips Bay Manhattan Manhattan
5870 2019-03-26 11:04:06 2019-03-26 11:09:23 1 0.64 5.5 1.26 0.0 7.56 green credit card Morningside Heights Manhattanville Manhattan Manhattan
686 2019-03-27 15:02:00 2019-03-27 15:31:19 1 3.79 20.0 0.00 0.0 23.30 yellow cash East Chelsea Manhattan Valley Manhattan Manhattan
4937 2019-03-02 19:50:23 2019-03-02 20:04:19 2 1.60 10.0 2.75 0.0 16.55 yellow credit card TriBeCa/Civic Center East Village Manhattan Manhattan
2659 2019-03-18 21:36:06 2019-03-18 21:48:31 1 1.10 8.0 0.00 0.0 11.80 yellow cash Midtown North Midtown North Manhattan Manhattan
#checks if two rows have the same name 
#returns true if there are no repeats
df.index.is_unique
True
good_inds = []

for i in df.index:
    try:
        if ("Airport" in df.loc[i,"pickup_zone"]) and ("Airport" in df.loc[i,"dropoff_zone"]):
            good_inds.append(i)
    except TypeError:
        continue
good_inds
[2387, 1080, 120, 5364, 1929, 3571, 1416, 4358, 1089, 5095, 770]
df.loc[good_inds]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
2387 2019-03-28 15:58:52 2019-03-28 15:59:25 1 1.80 69.06 20.80 0.00 90.16 yellow credit card JFK Airport JFK Airport Queens Queens
1080 2019-03-04 14:17:05 2019-03-04 14:17:13 1 0.00 2.50 0.00 0.00 3.30 yellow cash JFK Airport JFK Airport Queens Queens
120 2019-03-21 17:21:44 2019-03-21 17:21:49 1 0.00 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens
5364 2019-03-17 16:59:17 2019-03-17 18:04:08 2 36.70 150.00 0.00 24.02 174.82 yellow cash JFK Airport JFK Airport Queens Queens
1929 2019-03-13 22:35:35 2019-03-13 22:35:49 1 0.00 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens
3571 2019-03-22 16:47:41 2019-03-22 16:47:50 1 0.81 66.00 0.00 0.00 66.80 yellow credit card JFK Airport JFK Airport Queens Queens
1416 2019-03-09 13:16:32 2019-03-09 13:46:11 2 12.39 35.00 0.00 0.00 35.80 yellow cash LaGuardia Airport JFK Airport Queens Queens
4358 2019-03-06 18:24:00 2019-03-06 18:24:13 2 0.01 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens
1089 2019-03-10 01:43:32 2019-03-10 01:45:22 1 0.37 3.50 0.00 0.00 4.80 yellow cash JFK Airport JFK Airport Queens Queens
5095 2019-03-30 20:14:44 2019-03-30 21:01:28 3 18.91 52.00 8.78 5.76 67.34 yellow credit card JFK Airport JFK Airport Queens Queens
770 2019-03-02 03:16:59 2019-03-02 03:17:06 0 9.40 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens

Strings in pandas revisited: Worse approach 3 (helper function and map)#

We start now by writing a helper function which checks if the word “Airport” is contained in a given string.

def has_airport(s):
    return "Airport" in s
has_airport("Math 10")
False
has_airport("Los Angeles International Airport")
True

Let’s now define ser1 and ser2 to be the Series that we’re looking at:

ser1 = df["pickup_zone"]
ser2 = df["dropoff_zone"]
#how does map work?
help(ser1.map)
Help on method map in module pandas.core.series:

map(arg, na_action=None) -> 'Series' method of pandas.core.series.Series instance
    Map values of Series according to an input mapping or function.
    
    Used for substituting each value in a Series with another value,
    that may be derived from a function, a ``dict`` or
    a :class:`Series`.
    
    Parameters
    ----------
    arg : function, collections.abc.Mapping subclass or Series
        Mapping correspondence.
    na_action : {None, 'ignore'}, default None
        If 'ignore', propagate NaN values, without passing them to the
        mapping correspondence.
    
    Returns
    -------
    Series
        Same index as caller.
    
    See Also
    --------
    Series.apply : For applying more complex functions on a Series.
    DataFrame.apply : Apply a function row-/column-wise.
    DataFrame.applymap : Apply a function elementwise on a whole DataFrame.
    
    Notes
    -----
    When ``arg`` is a dictionary, values in Series that are not in the
    dictionary (as keys) are converted to ``NaN``. However, if the
    dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e.
    provides a method for default values), then this default is used
    rather than ``NaN``.
    
    Examples
    --------
    >>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit'])
    >>> s
    0      cat
    1      dog
    2      NaN
    3   rabbit
    dtype: object
    
    ``map`` accepts a ``dict`` or a ``Series``. Values that are not found
    in the ``dict`` are converted to ``NaN``, unless the dict has a default
    value (e.g. ``defaultdict``):
    
    >>> s.map({'cat': 'kitten', 'dog': 'puppy'})
    0   kitten
    1    puppy
    2      NaN
    3      NaN
    dtype: object
    
    It also accepts a function:
    
    >>> s.map('I am a {}'.format)
    0       I am a cat
    1       I am a dog
    2       I am a nan
    3    I am a rabbit
    dtype: object
    
    To avoid applying the function to missing values (and keep them as
    ``NaN``) ``na_action='ignore'`` can be used:
    
    >>> s.map('I am a {}'.format, na_action='ignore')
    0     I am a cat
    1     I am a dog
    2            NaN
    3  I am a rabbit
    dtype: object

Notice, we’ll still get an error because of the missing values.

ser1.map(has_airport)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [92], in <cell line: 1>()
----> 1 ser1.map(has_airport)

File ~/opt/miniconda3/envs/math9/lib/python3.9/site-packages/pandas/core/series.py:4237, in Series.map(self, arg, na_action)
   4162 def map(self, arg, na_action=None) -> Series:
   4163     """
   4164     Map values of Series according to an input mapping or function.
   4165 
   (...)
   4235     dtype: object
   4236     """
-> 4237     new_values = self._map_values(arg, na_action=na_action)
   4238     return self._constructor(new_values, index=self.index).__finalize__(
   4239         self, method="map"
   4240     )

File ~/opt/miniconda3/envs/math9/lib/python3.9/site-packages/pandas/core/base.py:880, in IndexOpsMixin._map_values(self, mapper, na_action)
    877         raise ValueError(msg)
    879 # mapper is a function
--> 880 new_values = map_f(values, mapper)
    882 return new_values

File ~/opt/miniconda3/envs/math9/lib/python3.9/site-packages/pandas/_libs/lib.pyx:2870, in pandas._libs.lib.map_infer()

Input In [87], in has_airport(s)
      1 def has_airport(s):
----> 2     return "Airport" in s

TypeError: argument of type 'float' is not iterable

Here’s how we can fix it:

#we see a lot of False, but that's just because we're
#looking at the first and last portions of the data
ser1.map(has_airport,na_action="ignore")
890     False
5870    False
686     False
4937    False
2659    False
        ...  
1180    False
3441    False
1344    False
4623    False
1289    False
Name: pickup_zone, Length: 6433, dtype: object
#Putting everything together
df[ser1.map(has_airport,na_action="ignore") & ser2.map(has_airport,na_action="ignore")]
pickup dropoff passengers distance fare tip tolls total color payment pickup_zone dropoff_zone pickup_borough dropoff_borough
2387 2019-03-28 15:58:52 2019-03-28 15:59:25 1 1.80 69.06 20.80 0.00 90.16 yellow credit card JFK Airport JFK Airport Queens Queens
1080 2019-03-04 14:17:05 2019-03-04 14:17:13 1 0.00 2.50 0.00 0.00 3.30 yellow cash JFK Airport JFK Airport Queens Queens
120 2019-03-21 17:21:44 2019-03-21 17:21:49 1 0.00 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens
5364 2019-03-17 16:59:17 2019-03-17 18:04:08 2 36.70 150.00 0.00 24.02 174.82 yellow cash JFK Airport JFK Airport Queens Queens
1929 2019-03-13 22:35:35 2019-03-13 22:35:49 1 0.00 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens
3571 2019-03-22 16:47:41 2019-03-22 16:47:50 1 0.81 66.00 0.00 0.00 66.80 yellow credit card JFK Airport JFK Airport Queens Queens
1416 2019-03-09 13:16:32 2019-03-09 13:46:11 2 12.39 35.00 0.00 0.00 35.80 yellow cash LaGuardia Airport JFK Airport Queens Queens
4358 2019-03-06 18:24:00 2019-03-06 18:24:13 2 0.01 2.50 0.00 0.00 4.30 yellow cash JFK Airport JFK Airport Queens Queens
1089 2019-03-10 01:43:32 2019-03-10 01:45:22 1 0.37 3.50 0.00 0.00 4.80 yellow cash JFK Airport JFK Airport Queens Queens
5095 2019-03-30 20:14:44 2019-03-30 21:01:28 3 18.91 52.00 8.78 5.76 67.34 yellow credit card JFK Airport JFK Airport Queens Queens
770 2019-03-02 03:16:59 2019-03-02 03:17:06 0 9.40 2.50 0.00 0.00 3.80 yellow NaN JFK Airport JFK Airport Queens Queens
Created in deepnote.com Created in Deepnote