数据中包含日期、时间类型的数据可以通过 pandas 的 to_datetime 转换成 datetime 类型,方便提取各种时间信息

1> 导入数据

import pandas as pd
car_sales = pd.read_csv('car_data.csv')

数据预处理 | 使用 pandas.to_datetime 处理时间类型的数据

 

 2> 查看 date_t 的数据类型

car_sales.date_t.dtype  #  'O' 代表 (Python) objects

数据预处理 | 使用 pandas.to_datetime 处理时间类型的数据

数据预处理 | 使用 pandas.to_datetime 处理时间类型的数据

3>  将 object 转 datetime64

car_sales['date'] = pd.to_datetime(car_sales['date_t'])

数据预处理 | 使用 pandas.to_datetime 处理时间类型的数据

 

 转换操作完成辽!

2 从 datetime 类型的数据中取出需要的时间信息

# 取出几月份
car_sales.loc[:,'month'] = car_sales['date'].dt.month

# 取出来是几号 dom:day of month
car_sales.loc[:,'dom'] = car_sales['date'].dt.day

# 取出一年当中的第几天 doy: day of year
car_sales.loc[:,'doy'] = car_sales['date'].dt.dayofyear

# 取出星期几 dow: day of week
car_sales.loc[:,'dow'] = car_sales['date'].dt.dayofweek

数据预处理 | 使用 pandas.to_datetime 处理时间类型的数据

 

相关文章:

猜你喜欢
  • 2022-01-07
  • 2022-12-23
  • 2021-11-26
  • 2021-11-23
相关资源
相似解决方案