重采样:指将时间序列从一个频率转换成另一个频率进行处理的过程。
高频到低频称降采样,低频到高频称升采样。
1.设置或者修改数据表 索引为“时间序列”
1.如果表里的数据是4列,分别为 年、月、日、时 首先 合并成str 型'2010-01-01 00:00'
periods=pd.PeriodIndex(year=data["year"],month=data["month"],day=data["day"],hour=data["hour"],freq="H")
2.增加时间序列
df["datetime"] = period
3.设为索引
df.set_index("datetime", inplace=True)
def readData():
#1.读取excel文件
filePath = "./data/PM2.5/BeijingPM20100101_20151231.csv"
df = pd.read_csv(filePath)
# 2.把年、月、日、时 通过 PeriodIndex的方法转化为 pandas的时间类型
period = pd.PeriodIndex(year=df["year"], month=df["month"], day=df["day"], hour=df["hour"], freq="H")
"""
print(period)
PeriodIndex(['2010-01-01 00:00', '2010-01-01 01:00', '2010-01-01 02:00',
'2010-01-01 03:00', '2010-01-01 04:00', '2010-01-01 05:00',
'2010-01-01 06:00', '2010-01-01 07:00', '2010-01-01 08:00',
'2010-01-01 09:00',
...
'2015-12-31 14:00', '2015-12-31 15:00', '2015-12-31 16:00',
'2015-12-31 17:00', '2015-12-31 18:00', '2015-12-31 19:00',
'2015-12-31 20:00', '2015-12-31 21:00', '2015-12-31 22:00',
'2015-12-31 23:00'],
dtype='period[H]', length=52584, freq='H')
"""
#3.创建新的时间列
df["datetime"] = period
# 4.把datetime 设置为索引
df.set_index("datetime", inplace=True)
# 5.进行降采样
df = df.resample("M").mean()
#df = df.resample("10D").count()
print(df)
#6. 处理缺失数据,删除缺失数据
# data = df[""].dropna()
2.降采样 高->低
原始数据:"2019-12-19 00:00:00" 每4小时一个值((10,50)随机值) 100个值
新数据: 按2天取一个值 (12个值取平均)
统计新频率数据个数()
t.resample("2D").mean()
t.resample("2D").count()
def resetFreq():
m_nums = 100
pdData = np.random.uniform(10, 50, (m_nums, 1))
pdIndex = pd.date_range(start="2019-12-19 00:00:00 ", periods=m_nums, freq='4H')# periods 个数 间隔时间freq
t = pd.DataFrame(pdData, pdIndex)
print(t)
print(t.resample("2D").mean()) # '2D'按‘2天’取平均值, 'M"按"月"取平均值
"""
2019-12-19 30.187593
2019-12-21 28.747335
2019-12-23 31.989311
2019-12-25 32.510580
2019-12-27 29.256347
2019-12-29 31.253162
2019-12-31 30.031848
2020-01-02 26.627749
2020-01-04 40.053487
"""
print(t.resample("2D").count())
"""
2019-12-19 12
2019-12-21 12
2019-12-23 12
2019-12-25 12
2019-12-27 12
2019-12-29 12
2019-12-31 12
2020-01-02 12
2020-01-04 4
"""