如何使用 at_time() 方法从 pandas.series 对象中选择值?

阅读 149 收藏 0 点赞 0 评论 0

Pandas方法用于在给定系列对象的特定时间选择值。该方法采用时间参数并返回具有选定值的系列对象。Series.at_time()at_time()

如果指定时间不在给定系列对象的索引中,at_time 方法将返回一个空系列对象,如果输入系列对象的索引没有 DatetimeIndex,它会引发 TypeError。

让我们使用 Datetime Index 创建一个 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("选择值:", 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

选择值:
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("选择值:", 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

选择值:
Series([], Freq: 30T, dtype: int64)

以下示例的输出是一个空系列对象,这是由于请求时间在给定系列对象的索引中不可用。

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号