Pandas怎样快捷方便的处理日期数据(二十)

Pandas日期处理的作用:将2018-01-01、1/1/2018等多种日期格式映射成统一的格式对象,在该对象上提供强大的功能支持

几个概念:

  • pd.to_datetime:pandas的一个函数,能将字符串、列表、series变成日期形式
  • Timestamp:pandas表示日期的对象形式
  • DatetimeIndex:pandas表示日期的对象列表形式

其中:

  • DatetimeIndex是Timestamp的列表形式
  • pd.to_datetime对单个日期字符串处理会得到Timestamp
  • pd.to_datetime对日期字符串列表处理会得到DatetimeIndex

问题:怎样统计每周、每月、每季度的最高温度?
1、读取天气数据到dataframe
import pandas as pd
%matplotlib inline

fpath = "./datas/beijing_tianqi/beijing_tianqi_2018.csv"
df = pd.read_csv(fpath)
# 替换掉温度的后缀℃
df.loc[:, "bWendu"] = df["bWendu"].str.replace("℃", "").astype('int32')
df.loc[:, "yWendu"] = df["yWendu"].str.replace("℃", "").astype('int32')
df.head()
2、将日期列转换成pandas的日期
df.set_index(pd.to_datetime(df["ymd"]), inplace=True)
df.index
# DatetimeIndex是Timestamp的列表形式
df.index[0]
3、 方便的对DatetimeIndex进行查询
# 筛选固定的某一天
df.loc['2018-01-05']

# 日期区间
df.loc['2018-01-05':'2018-01-10']

# 按月份前缀筛选
df.loc['2018-03']

# 按月份前缀筛选
df.loc["2018-07":"2018-09"].index

# 按年份前缀筛选
df.loc["2018"].head()
4、方便的获取周、月、季度

Timestamp、DatetimeIndex支持大量的属性可以获取日期分量:
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-date-components

# 周数字列表
df.index.week

# 月数字列表
df.index.month

# 季度数字列表
df.index.quarter
5、统计每周、每月、每个季度的最高温度

统计每周的数据

df.groupby(df.index.week)["bWendu"].max().head()
df.groupby(df.index.week)["bWendu"].max().plot()


统计每个月的数据

df.groupby(df.index.month)["bWendu"].max()
df.groupby(df.index.month)["bWendu"].max().plot()


统计每个季度的数据

df.groupby(df.index.quarter)["bWendu"].max()
df.groupby(df.index.quarter)["bWendu"].max().plot()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值