pandas.date_range(start=None, end=None, periods=None, freq='D', tz=None, normalize=False, name=None, closed=None, **kwargs)
该函数主要用于生成一个固定频率的时间索引,在调用构造方法时,必须指定start、end、periods中的两个参数值,否则报错。
主要参数说明:
- periods:固定时期,取值为整数或None
- freq:日期偏移量,取值为string或DateOffset,默认为'D'
- normalize:若参数为True表示将start、end参数值正则化到午夜时间戳
- name:生成时间索引对象的名称,取值为string或None
- closed:可以理解成在closed=None情况下返回的结果中,若closed=‘left’表示在返回的结果基础上,再取左开右闭的结果,若closed='right'表示在返回的结果基础上,再取做闭右开的结果
案例:
读取数据文件
#parse_dates参数告诉read_csv方法将第5列中的值作为日期读取,并转换为Numpy的datetime64对象。
transactions=pd.read_csv('mj-clean.csv',parse_dates=[5])
transactions.info()
输出:"date"字段为datetime64类型。
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 147070 entries, 0 to 147069
Data columns (total 10 columns):
city 147070 non-null object
state 147070 non-null object
price 147070 non-null int64
amount 147070 non-null float64
quality 147070 non-null object
date 147070 non-null datetime64[ns]
ppg 147070 non-null float64
state.name 147070 non-null object
lat 146897 non-null float64
lon 146897 non-null float64
dtypes: datetime64[ns](1), float64(4), int64(1), object(4)
memory usage: 9.0+ MB
接下我们将数据按照“date”进行聚合,将‘date"作为索引(index)。
daily=transactions.groupby('date')['city'].count().reset_index()
daily.index=daily['date']
daily
’输出:
绘图:
plt.plot(daily.index,daily['city'])
以上图发现,2013年10月至2013年12月直接是一条直线,可能是数据缺失,我们进一步验证数据。
现在我们想把daily的index,变成日历的形式,即日期范围内的每一天都对应一行,缺失数据用nan填充。
dates=pd.date_range(daily.index.min(),daily.index.max())
daily_new=daily.reindex(dates)
daily_new
plt.plot(daily_new.index,daily_new['city'])
以上图发现,2013年10月至2013年12月确实是数据缺失。为了数据进一步分析,接下来我们可以对数据缺失值处理,可运用“指数权重移动平均(简称EWMA)”来进行填充,其有两优点:首先,指数权重移动平均计算加权平均值,最近时间的值具有最高的权重,之前值的权重指数级降低;第二,pandas的EWMA实现可以较好地处理缺失值 。
以下是未进行缺失值处理的数据分布。
#定义函数:有放回的随机抽取样本元素
def Resample(xs,n):
return np.random.choice(xs,n, replace=True) #true表示有放回的重复抽样
#指数权重移动平均值
ewma_mean=daily_new['city'].ewm(span=30).mean() #span控制权重降低的速度,作用大致等同于滚动平均值的窗机大小。
#将reindexed中的NaN值用ewma填充。
resid=(daily_new['city']-ewma_mean).dropna() #计算残差,将reindexed['ppg']为NaN的去掉。
#增加噪音
fake_data=ewma_mean+Resample(resid,len(daily_new)) #将移动平均值和随机残差之和,作为新的数据
#缺失值填充
daily_new['city'].fillna(fake_data,inplace=True) #将reindexed['ppg']中的NaN替换为对应位置的fake_data数据
#画数据分布图
plt.scatter(daily_new.index,daily_new['city'])
输出: