如何使用 at_time() 方法從 pandas.series 物件中選擇值?


Pandas Series 的 at_time() 方法用於選擇給定序列物件特定時間的值。at_time() 方法接受一個時間引數,並返回一個包含所選值的序列物件。

如果指定的日期時間在給定序列物件的索引中不存在,則 at_time 方法將返回一個空的 Series 物件;如果輸入序列物件的索引不包含 DatetimeIndex,則會引發 TypeError 錯誤。

讓我們建立一個帶有 Datetime 索引的 pandas Series 物件,並使用 Series.at_time() 方法獲取值。如果指定的日期時間存在於給定輸入序列物件的索引中,則它將返回一個包含這些行值的序列物件。

示例 1

import pandas as pd

# create the index
index = pd.date_range('2021-01-1', periods=10, freq='6H')

#creating pandas Series with date-time index
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

# selecting values
print("Selecting values:", series.at_time("6:00"))

解釋

在以下示例中,使用 pandas DateTime 索引和一些整數列表建立序列。之後,我們應用 at_time() 方法以獲取時間“6:00”處的值。

輸出

2021-01-01 00:00:00  1
2021-01-01 06:00:00  2
2021-01-01 12:00:00  3
2021-01-01 18:00:00  4
2021-01-02 00:00:00  5
2021-01-02 06:00:00  6
2021-01-02 12:00:00  7
2021-01-02 18:00:00  8
2021-01-03 00:00:00  9
2021-01-03 06:00:00 10
Freq: 6H, dtype: int64

Selecting values:
2021-01-01 06:00:00  2
2021-01-02 06:00:00  6
2021-01-03 06:00:00 10
Freq: 24H, dtype: int64

在此示例中,我們已成功從給定的序列物件中選擇了 3 行,這 3 行在其索引標籤處具有時間“6:00”小時。

示例 2

import pandas as pd

# create the index
index = pd.date_range('2021-01-1', periods=10, freq='30T')

#creating pandas Series with date-time index
series = pd.Series([1,2,3,4,5,6,7,8,9,10], index=index)

print(series)

# selecting values
print("Selecting values:", series.at_time("00:10:00"))

解釋

同樣地,我們建立了一個帶有 pandas DateTime 索引的 pandas 物件。之後,我們嘗試在時間“00:10:00”處從序列獲取值。

輸出

2021-01-01 00:00:00  1
2021-01-01 00:30:00  2
2021-01-01 01:00:00  3
2021-01-01 01:30:00  4
2021-01-01 02:00:00  5
2021-01-01 02:30:00  6
2021-01-01 03:00:00  7
2021-01-01 03:30:00  8
2021-01-01 04:00:00  9
2021-01-01 04:30:00 10
Freq: 30T, dtype: int64

Selecting values:
Series([], Freq: 30T, dtype: int64)

以下示例的輸出是一個空序列物件,這是由於請求時間在給定序列物件的索引中不可用。

更新於: 2022年3月9日

87 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.