如何從 Pandas Series 中獲取特定時間段的值?


Pandas Series 的 `between_time()` 方法用於選擇一天中特定時間段的值。`between_time()` 方法接受兩個時間引數,並返回包含所選值的 Series 物件。

`between_time` 方法類似於 Pandas Series 物件的 `at_time` 方法,`at_time` 方法選擇特定時間的值,而 `between_time` 方法將選擇時間段內的值。

如果輸入 Series 物件的索引不是 DatetimeIndex,則會引發 TypeError。

預設情況下,兩個輸入時間 (start_time, end_time) 引數都是包含的,如果要更改此設定,可以使用 `include_start` 和 `include_end` 引數。

示例 1

import pandas as pd

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

#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 by between_time()
print("Selecting values:", series.between_time("00:10","1:40"))

解釋

在這裡,我們使用 Pandas DateTime 索引和一些整數列表建立了一個 pandas.Series 物件。之後,我們應用 `between_time()` 方法來獲取“00:10”到“1:40”之間的時間段的值。

如果給定 Series 物件的索引中存在指定的時間,則它將返回一個新的 Series 物件,其中包含具有這些 DateTime 索引的收集值。

輸出

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

Selecting values:
2021-01-01 00:20:00 2
2021-01-01 00:40:00 3
2021-01-01 01:00:00 4
2021-01-01 01:20:00 5
2021-01-01 01:40:00 6
Freq: 20T, dtype: int64

我們收集了“00:10”到“1:40”之間的時間段的值。在此示例中,start_time (“00:10”) 和 end_time (“1:40”) 都包含在內。

示例 2

import pandas as pd

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

#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 by between_time()
print("Selecting values:", series.between_time("00:40","1:40", include_start=False,include_end=False))

解釋

在下面的示例中,我們透過不包含起始和結束時間來應用 `between_time()` 方法,這是透過向 `include_start` 和 `include_end` 引數提供 False 值來完成的。

輸出

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

Selecting values:
2021-01-01 01:00:00 4
2021-01-01 01:20:00 5
Freq: 20T, dtype: int64

在此示例中,我們已成功從給定的 Series 物件中選擇了 2 行,這 3 行的 DateTime 索引時間介於“00:40”和“1:40”之間,這兩個時間都不包含在內。

更新於:2022年3月9日

266 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.