首先引入相关的包
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
from datetime import datetime
创建一个时间对象
t1 = datetime(2009,10,20,0,0)
print(t1)
创建多个时间对象
date_list = [
datetime(2016,9,1),
datetime(2017,9,2),
datetime(2016,9,3),
datetime(2017,9,4),
datetime(2016,10,5),
]
print(date_list)
打印结果
[datetime.datetime(2016, 9, 1, 0, 0), datetime.datetime(2017, 9, 2, 0, 0), datetime.datetime(2016, 9, 3, 0, 0), datetime.datetime(2017, 9, 4, 0, 0), datetime.datetime(2016, 10, 5, 0, 0)]
2016-09-01 0.257473
创建一个以date_list为index的Serious并且查看他的相关信息
s1 = Series(np.random.rand(5),index=date_list)
print(s1)
print(type(s1))
print(s1.index)
print(s1.values)
print(s1[1])
print(s1[datetime(2016,9,1)])
print(s1['2016-9-1'])
print(s1['2016-9'])
print('-'*100)
print(s1['2017'])
date_list_new = pd.date_range('2016-01-01',periods=100)
date_list_new = pd.date_range('2016-01-01',periods=100,freq='5H')
s2 = Series(np.random.rand(100),index=date_list_new)
print(s2)
首先引入相关包
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
创建一下date_list_new
#创建一下date_list_new
t_range = pd.date_range('2016-01-01','2016-12-31')
print(t_range)
print(len(t_range))
s1 = Series(np.random.randn(len(t_range)),index = t_range)
print(s1)
#对它进行采样
print(s1['2016-01'])#获取到一月份的数据
print(s1['2016-01'].mean())
#算12次 就实现采样的功能 然而有更好的
函数采样
按月采样
s1_month = s1.resample('M').mean()
print(s1_month)
print(s1_month.index)
#一天采集24个点,提高采样率
#填充方式
print(s1.resample('H').ffill())
另一种填充方式
#另一种填充方式
print(s1.resample('H').bfill())
画时序图
#画时序图
import matplotlib.pyplot as plt
t_range = pd.date_range('2016-01-01','2016-12-31',freq='H')
print(t_range)
#股票
stock_df = DataFrame(index=t_range)
stock_df['BABA'] = np.random.randint(80,160,size = len(t_range))
#print(stock_df)
print(stock_df.head())
stock_df['TENCENT'] = np.random.randint(80,160,size = len(t_range))
stock_df.plot()
plt.show()
weekly_df = DataFrame()
然后周平均,并绘图
weekly_df = DataFrame()
weekly_df['BABA'] = stock_df['BABA'].resample('W').mean()
weekly_df['TENCENT'] = stock_df['TENCENT'].resample('W').mean()
print(weekly_df.head())
weekly_df.plot()