Pandas2.2 Series
Time Series-related
方法 | 描述 |
---|---|
Series.asfreq(freq[, method, how, …]) | 用于将时间序列数据转换为指定的频率 |
Series.asof(where[, subset]) | 用于返回时间序列中指定索引位置的最近一个非缺失值 |
pandas.Series.asof
pandas.Series.asof
方法用于返回时间序列中指定索引位置的最近一个非缺失值。它特别适用于处理不规则时间间隔的数据,可以找到在给定时间点之前最近的有效(非缺失)观测值。
详细描述
- 参数:
where
: 类似数组或标量,表示要查询的时间点或时间点列表。subset
: 可选,默认为None
。如果提供,则只考虑这些列中的非缺失值来确定最近的有效行。
返回值
- 返回一个新的
Series
或标量值,具体取决于where
参数:- 如果
where
是标量,则返回标量值。 - 如果
where
是数组,则返回与where
形状相同的Series
。
- 如果
示例代码及结果
import pandas as pd
import numpy as np# 创建一个带有日期索引的时间序列,包含一些缺失值
dates = pd.to_datetime(['2023-10-01', '2023-10-03', '2023-10-05', '2023-10-07', '2023-10-09'])
s = pd.Series([1, 2, np.nan, 4, 5], index=dates)print("原始 Series:")
print(s)# 查询特定时间点的最近非缺失值
query_date_1 = pd.Timestamp('2023-10-04')
result_1 = s.asof(query_date_1)print("\n查询 2023-10-04 的最近非缺失值:")
print(result_1)# 查询多个时间点的最近非缺失值
query_dates = pd.to_datetime(['2023-10-02', '2023-10-06', '2023-10-10'])
result_2 = s.asof(query_dates)print("\n查询多个时间点的最近非缺失值:")
print(result_2)
输出结果
原始 Series:
2023-10-01 1
2023-10-03 2
2023-10-05 3
2023-10-07 4
2023-10-09 5
Freq: 2D, dtype: int64转换为每日频率并前向填充后的 Series:
2023-10-01 1
2023-10-02 1
2023-10-03 2
2023-10-04 2
2023-10-05 3
2023-10-06 3
2023-10-07 4
2023-10-08 4
2023-10-09 5
Freq: D, dtype: int64
结果解释
- 在示例中,原始
Series
包含一些缺失值 (NaN
)。 - 使用
asof
方法查询特定时间点(如2023-10-04
)时,它会返回该时间点之前最近的非缺失值,即2.0
。 - 对于多个时间点的查询,
asof
方法返回每个时间点之前最近的非缺失值:2023-10-02
之前最近的非缺失值是1.0
。2023-10-06
之前最近的非缺失值是2.0
。2023-10-10
之前最近的非缺失值是5.0
。
这种方法非常适用于金融数据等需要处理不规则时间间隔和缺失值的场景。