Creating a DatetimeIndex

Analyzing Police Activity with pandas

Kevin Markham

Founder, Data School

Using datetime format

ri.head(3)
    stop_date stop_time driver_gender driver_race
0  2005-01-04     12:55             M       White
1  2005-01-23     23:15             M       White
2  2005-02-17     04:15             M       White
ri.dtypes
stop_date             object
stop_time             object
driver_gender         object
driver_race           object
...
  1. Combine stop_date and stop_time into one column
  2. Convert it to datetime format
Analyzing Police Activity with pandas

Combining object columns

apple
      date   time   price
0  2/13/18  16:00  164.34
1  2/14/18  16:00  167.37
2  2/15/18  16:00  172.99
apple.date.str.replace('/', '-')
0    2-13-18
1    2-14-18
2    2-15-18
Name: date, dtype: object
combined =
  apple.date.str.cat(apple.time, sep=' ')
combined
0    2/13/18 16:00
1    2/14/18 16:00
2    2/15/18 16:00
Name: date, dtype: object
Analyzing Police Activity with pandas

Converting to datetime format

apple['date_and_time'] = pd.to_datetime(combined)

apple
      date   time   price        date_and_time
0  2/13/18  16:00  164.34  2018-02-13 16:00:00
1  2/14/18  16:00  167.37  2018-02-14 16:00:00
2  2/15/18  16:00  172.99  2018-02-15 16:00:00
apple.dtypes
date                     object
time                     object
price                   float64
date_and_time    datetime64[ns]
Analyzing Police Activity with pandas

Setting the index

apple.set_index('date_and_time', inplace=True)

apple
                        date   time   price
date_and_time                              
2018-02-13 16:00:00  2/13/18  16:00  164.34
2018-02-14 16:00:00  2/14/18  16:00  167.37
2018-02-15 16:00:00  2/15/18  16:00  172.99
apple.index
DatetimeIndex(['2018-02-13 16:00:00', '2018-02-14 16:00:00',
               '2018-02-15 16:00:00'],
              dtype='datetime64[ns]', name='date_and_time', freq=None)
Analyzing Police Activity with pandas

Let's practice!

Analyzing Police Activity with pandas

Preparing Video For Download...