当前位置:主页 > 软件编程 > Python代码 >

pandas进行时间数据的转换和计算时间差并提取年月日

时间:2021-07-15 09:28:52 | 栏目:Python代码 | 点击:

#pd.to_datetime函数

#读取数据
import pandas as pd
data = pd.read_csv('police.csv')
 
#将stop_date转化为datetime的格式的dataframe,存到stop_datetime
data['stop_datetime'] = pd.to_datetime(data.stop_date')

#自定义一个时间,计算时间差

data_new = pd.to_datetime('2006-01-01')
data['time_d'] = time_new - data.stop_datetime
data['time_d'].head()

#统计各年份和月份出现的次数

data.stop_datetime.dt.year.value_counts()
data.stop_datetime.dt.month.value_counts()

#提取年、月、日

#提取年
data['year'] = data.stop_datetime.dt.year
data['year'].head()
 
#提取月份
data['month'] = data.stop_datetime.dt.month
data['month'].head()
 
#提取日
data['day'] = data.stop_datetime.dt.day
data['day'].head()

#使用时间序列数据绘图

data['stop_time_datetime'] = pd.to_datetime(data.stop_time)
data.groupby(data.stop_time_datetime.dt.hour).drugs_related_stop.sum().plot()

您可能感兴趣的文章:

相关文章