如何在 Pandas Series 中訪問日期時間索引的元素?
Pandas Series 是一種一維 ndarray 型別物件,它儲存帶有標籤的元素,這些標籤用於定址 Pandas Series 中存在的元素。
標籤用整數、字串、DateTime 等表示。這裡我們將看到如果索引用 DateTime 值標記,如何訪問 Series 元素。
示例
import pandas as pd
# creating dates
date = pd.date_range("2021-01-01", periods=5, freq="D")
# creating pandas Series with date index
series = pd.Series(range(10,len(date)+10), index=date)
print(series)
print('
')
# get elements
print(series['2021-01-01'])解釋
變數 date 儲存長度為 5 的日期列表,起始日期為 2021-01-01,結束日期為 2021-01-05。這些日期是使用 pandas 的 date_range 函式建立的。使用此日期列表,我們建立了一個 Pandas Series 物件 (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
# creating dates
date = pd.date_range(start ='01-03-2020', end ='1-1-2021', periods=10)
# creating pandas Series with date index
series = pd.Series(date.month_name(), index=date)
print(series)
print('
')
# get 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
輸出 march 是透過指定年份和月份值 (series['2020-03']) 訪問的 Series 元素。上面的輸出塊包含整個 Series 物件和單個訪問的元素。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP