如何访问 pandas 系列中的日期时间索引元素?
Pandas 系列是一个一维 ndarray 类型对象,它存储带有标签的元素,这些标签用于寻址 pandas 系列中存在的元素。
标签用整数、字符串、日期时间等表示。在这里,我们将看到如果索引标有 DateTime 值,如何访问系列元素。
示例
import pandas as pd # 创建日期 date = pd.date_range("2021-01-01", periods=5, freq="D") # 创建带有日期索引的 pandas 系列 series = pd.Series(range(10,len(date)+10), index=date) print(series) print('
') # 获取元素 print(series['2021-01-01'])
解释
变量 date 存储长度为 5 的日期列表,起始日期为2021-01-01,结束日期为 2021-01-05。这些日期是使用 pandas date_range 函数创建的。通过这个日期列表,我们创建了一个 pandas 系列对象(series),其值有 10、11、12、13、14,标签是日期。
输出
2021-01-01 10 2021-01-02 11 2021-01-03 12 2021-01-04 13 2021-01-05 14 Freq: D, dtype: int64 10
在下面的示例中,索引为 '2021-01-01' 的标签显示值 10。用同样的方式,我们可以访问日期之间的元素(series[‘2021-01-01’: ‘2021-01-05’])
示例
此示例用于根据特定月份访问元素。
import pandas as pd # 创建日期 date = pd.date_range(start ='01-03-2020', end ='1-1-2021', periods=10) # 创建带有日期索引的 pandas Series series = pd.Series(date.month_name(), index=date) print(series) print('
') # 获取elements print(series['2020-03'])
解释
series 对象存储的是带有 DateTime 索引标签和其各自月份名称的数据。最初,此 series 对象是使用 pandas date_range 模块创建的。
并且此 series 中存在的数据是使用 pandas DateTime 模块中的 month_name() 函数生成的相应索引标签的月份名称。
输出
2020-01-03 00:00:00 January 2020-02-12 10:40:00 February 2020-03-23 21:20:00 March 2020-05-03 08:00:00 May 2020-06-12 18:40:00 June 2020-07-23 05:20:00 July 2020-09-01 16:00:00 September 2020-10-12 02:40:00 October 2020-11-21 13:20:00 November 2021-01-01 00:00:00 January dtype: object 2020-03-23 21:20:00 March dtype: object
The output march is series elements accessed by specifying the year and month values (series['2020-03']). The above output block has an entire series object and a single accessed element.