将日数据转为周数据:to_period, resample

编程入门 行业动态 更新时间:2024-10-21 18:51:47

to_period

第一步:数据

a = pd.date_range('8/5/2021',periods=12,freq='D')
b = ['业务线'+str(i) for i in range(1,3)]
b = np.array([random.choice(b) for i in range(len(a))])
c = np.random.randint(1, 3, size=len(a))
df = pd.DataFrame({'时间':a,'分类':b,'值':c})
df

第二步:时间转换为索引,日期转换为周 (df.to_period)

df2 = df.set_index('时间').to_period(freq='W-THU')#以周五开始--THU
df2

 

第三步:分类

df3 = df2.groupby(['时间','分类']).count()
df3

 

第四步:为画图准备数据

#plotnine画图数据
df4=df3.reset_index()
df4

 

#plt画图数据
df5=df4.pivot('时间','分类','值').reset_index()
df5

 

resample 重采样

data = df.set_index('时间')
data1 =data.groupby('分类').resample('W-FRI',closed='left',label='left').count()#closed='left',[左闭右开)
data1.swaplevel().sort_index(level='时间')

 

resample注意:各个时间段都是半开放的,一个数据点只能属于一个时间段。要考虑两点:①各区间哪边闭合;②标记用区间开头还是结尾

举例

#数据
rng = pd.date_range('2000-01-01',periods=10,freq='D')
ts = pd.Series(np.arange(1,11),index=rng)
ts

2000-01-01     1
2000-01-02     2
2000-01-03     3
2000-01-04     4
2000-01-05     5
2000-01-06     6
2000-01-07     7
2000-01-08     8
2000-01-09     9
2000-01-10    10
Freq: D, dtype: int64

左边闭合

ts.resample('4D',closed='left',label='left').sum()#同为左较方便

2000-01-01    10 #2000-01-01~2000-01-04 (1,2,3,4)
2000-01-05    26 #2000-01-05~2000-01-08 (5,6,7,8)
2000-01-09    19 #2000-01-09~2000-01-12 (9,10)
Freq: 4D, dtype: int64

 右边闭合

ts.resample('4D',closed='right',label='left').sum()

1999-12-28     1 #1999-12-29~2000-01-01 (1)
2000-01-01    14 #2000-01-02~2000-01-05 (2,3,4,5)
2000-01-05    30 #2000-01-06~2000-01-09 (6,7,8,9)
2000-01-09    10 #2000-01-10~2000-01-13 (10)
Freq: 4D, dtype: int64

 

更多推荐

将日数据转为周数据:to_period, resample

本文发布于:2023-06-11 02:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1372313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日数   数据   resample   to_period

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!