详解如何使用Pandas处理时间序列数据
作者:Alex_StarSky
Pandas-如何轻松处理时间序列数据
时间序列数据在数据分析建模中很常见,例如天气预报,空气状态监测,股票交易等金融场景。此处选择巴黎、伦敦欧洲城市空气质量监测NO2数据作为样例。
监测的时间序列数据
比如,air quality no2 数据表中,主要是巴黎,伦敦等城市的每小时环境监测数据:
In [2]: air_quality.head()
Out[2]: 
    city country                   datetime location parameter  value   unit
0  Paris      FR  2019-06-21 00:00:00+00:00  FR04014       no2   20.0  µg/m³
1  Paris      FR  2019-06-20 23:00:00+00:00  FR04014       no2   21.8  µg/m³
2  Paris      FR  2019-06-20 22:00:00+00:00  FR04014       no2   26.5  µg/m³
3  Paris      FR  2019-06-20 21:00:00+00:00  FR04014       no2   24.9  µg/m³
4  Paris      FR  2019-06-20 20:00:00+00:00  FR04014       no2   21.4  µg/m³
In [3]: air_quality.city.unique()
Out[3]: array(['Paris', 'Antwerpen', 'London'], dtype=object)
转换为日期时间对象
默认读取的日期数据,实际上是字符串string 类型,无法进行日期时间的操作,可以转换为datetime数据对象类型,可以用to_datetime() 函数这样操作:
In [5]: air_quality["datetime"] = pd.to_datetime(air_quality["datetime"])
In [6]: air_quality["datetime"]
Out[6]: 
0      2019-06-21 00:00:00+00:00
1      2019-06-20 23:00:00+00:00
2      2019-06-20 22:00:00+00:00
3      2019-06-20 21:00:00+00:00
4      2019-06-20 20:00:00+00:00
                  ...           
2063   2019-05-07 06:00:00+00:00
2064   2019-05-07 04:00:00+00:00
2065   2019-05-07 03:00:00+00:00
2066   2019-05-07 02:00:00+00:00
2067   2019-05-07 01:00:00+00:00
Name: datetime, Length: 2068, dtype: datetime64[ns, UTC]
当然,也可以在pandas.read_csv(), 和 pandas.read_json()函数中,直接就解析转换为datetime类型,parse_dates 参数
pd.read_csv("../data/air_quality_no2_long.csv", parse_dates=["datetime"])
时间操作的典型问题
如何找到序列中的时间开始和时间结束?
In [7]: air_quality["datetime"].min(), air_quality["datetime"].max()
Out[7]: 
(Timestamp('2019-05-07 01:00:00+0000', tz='UTC'),
 Timestamp('2019-06-21 00:00:00+0000', tz='UTC'))
通过min()函数,找到时间最小值,也就是开始时间;max()函数,找到时间序列最大值,也就是结束时间。
如何比较两个时间点?如何计算时间跨度,或者持续时间?
In [8]: air_quality["datetime"].max() - air_quality["datetime"].min()
Out[8]: Timedelta('44 days 23:00:00')
pandas.Timestamp 可以直接计算差值,结果为pandas.Timedelta 类型,类似于python库的时间跨度,datetime.timedelta
如何仅关注某个时间单位?
比如年,月,日,比如增加一列,表示月份?
In [11]: air_quality["month"] = air_quality["datetime"].dt.month
In [12]: air_quality.head()
Out[12]: 
    city country                  datetime  ... value   unit  month
0  Paris      FR 2019-06-21 00:00:00+00:00  ...  20.0  µg/m³      6
1  Paris      FR 2019-06-20 23:00:00+00:00  ...  21.8  µg/m³      6
2  Paris      FR 2019-06-20 22:00:00+00:00  ...  26.5  µg/m³      6
3  Paris      FR 2019-06-20 21:00:00+00:00  ...  24.9  µg/m³      6
4  Paris      FR 2019-06-20 20:00:00+00:00  ...  21.4  µg/m³      6
[5 rows x 8 columns]
使用timestamp的 dt.month属性,提取月份数值。类似的,也可以提取年,日,季节等等时间属性。
如何计算每周,每个城市的No2浓度平均值?
In [13]: air_quality.groupby(
   ....:     [air_quality["datetime"].dt.weekday, "location"])["value"].mean()
   ....: 
Out[13]: 
datetime  location          
0         BETR801               27.875000
          FR04014               24.856250
          London Westminster    23.969697
1         BETR801               22.214286
          FR04014               30.999359
                                  ...    
5         FR04014               25.266154
          London Westminster    24.977612
6         BETR801               21.896552
          FR04014               23.274306
          London Westminster    24.859155
Name: value, Length: 21, dtype: float64
使用groupby函数,按照周为时间单位,按城市分组然后合并归集,计算组内均值。
如何把时间Datetime作为索引?
In [18]: no_2 = air_quality.pivot(index="datetime", columns="location", values="value") In [19]: no_2.head() Out[19]: location BETR801 FR04014 London Westminster datetime 2019-05-07 01:00:00+00:00 50.5 25.0 23.0 2019-05-07 02:00:00+00:00 45.0 27.7 19.0 2019-05-07 03:00:00+00:00 NaN 50.4 19.0 2019-05-07 04:00:00+00:00 NaN 61.9 16.0 2019-05-07 05:00:00+00:00 NaN 72.4 NaN
pivot()函数,指定索引 index,列属性columns和数值values,生成二维表。
另外,也可以通过set_index函数。
如何更新频度的重采样?
比如,把当前每小时的采样频度,更新为每个月,取最大值作为采样值。
In [22]: monthly_max = no_2.resample("M").max()
In [23]: monthly_max
Out[23]: 
location                   BETR801  FR04014  London Westminster
datetime                                                       
2019-05-31 00:00:00+00:00     74.5     97.0                97.0
2019-06-30 00:00:00+00:00     52.5     84.7                52.0
resample()函数,类似于groupby分组聚合函数。
以上代码只是一个简单示例,示例代码中的表达式可以根据实际问题进行修改。
到此这篇关于详解如何使用Pandas处理时间序列数据的文章就介绍到这了,更多相关Pandas处理时间序列数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
