pandas学习笔记(三)

pandas时期:period

pd.period()创建时期

#生成一个以2017-01开始,月为频率的时间构造器
#pd.Period()参数:一个时间戳+freq
p=pd.Period('2017',freq='M')
print(p)

#通过加减整数,将周期整体移动
print(p+1)
print(p-2)

输出:
2017-01
2017-02
2016-11

pd.period_range()创建时期范围


prng=pd.period_range('1/1/2011','1/1/2012',freq='M')
print(prng)

PeriodIndex([‘2011-01’, ‘2011-02’, ‘2011-03’, ‘2011-04’, ‘2011-05’, ‘2011-06’,’2011-07’, ‘2011-08’, ‘2011-09’, ‘2011-10’, ‘2011-11’, ‘2011-12’,’2012-01’],
dtype=’period[M]’, freq=’M’)

频率转换asfreq

p=pd.Period('2017','A-DEC')
print(p)
print(p.asfreq('M',how='start')) #等于how='s'
print(p.asfreq('D',how='end'))  #等于how='e'

输出:
2017
2017-01
2017-12-31

时间戳与时期直接的转换:pd.to_period(),pd.to_timestamp()

#每月最后一日,转换为每月
r=pd.date_range('2017/1/1',periods=10,freq='M')
pr=pd.period_range('2017','2018',freq='M')

ts1=pd.Series(np.random.rand(len(r)),index=r)
print(ts1.head())
print(ts1.to_period().head())

#每月转化为每月第一天
ts2=pd.Series(np.random.rand(len(pr)),index=pr)
print(ts2.head())
print(ts2.to_timestamp().head())

输出:
2017-01-31 0.294556
2017-02-28 0.037492
2017-03-31 0.219091
2017-04-30 0.742907
2017-05-31 0.242779
Freq: M, dtype: float64

2017-01 0.294556
2017-02 0.037492
2017-03 0.219091
2017-04 0.742907
2017-05 0.242779
Freq: M, dtype: float64

2017-01 0.588072
2017-02 0.648728
2017-03 0.457712
2017-04 0.452702
2017-05 0.159034
Freq: M, dtype: float64

2017-01-01 0.588072
2017-02-01 0.648728
2017-03-01 0.457712
2017-04-01 0.452702
2017-05-01 0.159034
Freq: MS, dtype: float64

时间序列:索引及切片

r=pd.date_range('2017/1','2017/3')
ts=pd.Series(np.random.rand(len(r)))
print(ts.head())
print(ts[:2])
print(ts[::2])

时间序列-重采样

将时间序列从一个频率转换为另一个频率的过程,且会有数据的结合
降采样:高频数据->低频数据,eg:以天为频率转换为以月为频率
升采样:低频数据->高频数据,eg:以年为频率的数据转换为以月为频率的数据

重采样.resample()

r=pd.date_range('20170101',periods=12)
ts=pd.Series(np.arange(12),index=r)
print(ts)

ts_re=ts.resample('5D')
ts_re1=ts.resample('5D').sum() #聚合方法

print(ts.resample('5D').mean()) #求平均值
print(ts.resample('5D').max()) #求最大值
print(ts.resample('5D').median()) #求中值
print(ts.resample('5D').first()) #返回第一个值
print(ts.resample('5D').last()) #返回最后一个值
print(ts.resample('5D').min()) #求最小值

降采样

r=pd.date_range('20170101',periods=12)
ts=pd.Series(np.arange(1,13),index=r)
print(ts)

print(ts.resample('5D').sum())
print(ts.resample('5D',closed='left').sum())
#colosed:指定间隔,可以选左闭合或者右闭合


print(ts.resample('5D',label='left').sum())
#label:聚合值的index,默认取左

升采样及插值

r=pd.date_range('2017/1/1 0:0:0',periods=5,freq='H')
ts=pd.DataFrame(np.arange(15).reshape(5,3),index=r,columns=['a','b','c'])

print(ts)
print(ts.resample('15T').asfreq()) #不做填充返回Nan
print(ts.resample('15T').ffill())   #向上填充
print(ts.resample('15T').bfill()) #向下填充

时期重采样-Period

pr=pd.period_range('2016','2017',freq='M')
ts=pd.Series(np.arange(len(pr)),index=pr)

print(ts.resample('3M').sum())  #降采样
print(ts.resample('15D').ffill())  #升采样

你可能感兴趣的:(数据分析,python)