Python3数据科学汇总: https://blog.youkuaiyun.com/weixin_41793113/article/details/99707225
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
t_range = pd.date_range('2016-01-01', '2016-12-31')
t_range ##生成时间序列
s1 = Series(np.random.randn(len(t_range)), index=t_range) ##以时间序列为索引生成Series
s1['2016-01'].mean() ##求2016-01月的平均值
s1_month = s1.resample('M').mean() ##改变采样频率为月
s1_month.index
s1.resample('H').bfill() ##以'H'小时重新采样,以上一个非空数据填充
t_range = pd.date_range('2016-01-01', '2016-12-31', freq='H') #从2016-01-01到2016-12-31以小时采样时间序列
t_range
# 建立一个DataFrame
stock_df = DataFrame(index=t_range)
# 加入两行,模拟股票
stock_df['BABA'] = np.random.randint(80, 100, size=len(t_range))
stock_df['TENCENT'] = np.random.randint(30, 50, size=len(t_range))
stock_df
stock_df.plot() ##画图
import matplotlib.pyplot as plt
%matplotlib inline
plt.show()
weekly_df = DataFrame() ##创建空的DataFrame
weekly_df['BABA'] = stock_df['BABA'].resample('W').mean() ##以周为频率重新采样
weekly_df['TENCENT'] = stock_df['TENCENT'].resample('W').mean()
weekly_df.head()
weekly_df.plot()