pandas#03-时间序列

生成一段时间范围

pd.date_range(start=None, end=None, periods=None, freq=‘D’)

start和end以及freq配合能够生成start和end范围内以频率freq的一组时间索引
start和periods以及freq配合能够生成从start开始的频率为freq的periods个时间索引

关于频率的更多缩写

在这里插入图片描述

在DataFrame中使用时间序列

index=pd.date_range(“20170101”,periods=10)
df = pd.DataFrame(np.random.rand(10),index=index)

可以使用pandas提供的方法把时间字符串转化为时间序列

df[“timeStamp”] = pd.to_datetime(df[“timeStamp”],format="")

format参数大部分情况下可以不用写,但是对于pandas无法格式化的时间字符串,我们可以使用该参数,比如包含中文

pandas重采样

**重采样:**指的是将时间序列从一个频率转化为另一个频率进行处理的过程,将高频率数据转化为低频率数据为降采样,低频率转化为高频率为升采样

pandas提供了一个resample的方法来帮助我们实现频率转化
在这里插入图片描述

#例1.2015到2017年25万条911的紧急电话的数据,统计出不同月份不同类型紧急电话的次数的变化情况

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

#把时间字符串转为时间类型设置为索引
df=pd.read_csv("./911.csv")
df["timeStamp"] = pd.to_datetime(df["timeStamp"])

#print(df.head(10))
#print(df.info())

#添加列,表示分类
temp_list=df["title"].str.split(": ").tolist()
cate_list = [i[0] for i in temp_list]
#print(cate_list)
df["cate"] = pd.DataFrame(np.array(cate_list).reshape((df.shape[0],1)))
#print(df.head(5))
df.set_index("timeStamp",inplace=True)

plt.figure(figsize=(20,8),dpi=80)
#分组
for group_name,group_data in df.groupby(by="cate"):
    count_by_month = group_data.resample("M").count()["title"]

# 画图
    _x = count_by_month.index
    print(_x)
    _y = count_by_month.values

    _x = [i.strftime("%Y%m%d") for i in _x]

    plt.plot(range(len(_x)), _y, label=group_name)


plt.xticks(range(len(_x)), _x, rotation=45)
plt.legend(loc="best")
plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值