python - 为不规则间隔的数据找到最接近特定时间的每日观察

标签 python pandas time

我有一个类似 python 的数据框

Out[110]:
Time
2014-09-19 21:59:14    55.975
2014-09-19 21:56:08    55.925
2014-09-19 21:53:05    55.950
2014-09-19 21:50:29    55.950
2014-09-19 21:50:03    55.925
2014-09-19 21:47:00    56.150
2014-09-19 21:53:57    56.225
2014-09-19 21:40:51    56.225
2014-09-19 21:37:50    56.300
2014-09-19 21:34:46    56.300
2014-09-19 21:31:41    56.350
2014-09-19 21:30:08    56.500
2014-09-19 21:28:39    56.375
2014-09-19 21:25:34    56.350
2014-09-19 21:22:32    56.400
2014-09-19 21:19:27    56.325
2014-09-19 21:16:25    56.325
2014-09-19 21:13:21    56.350
2014-09-19 21:10:18    56.425
2014-09-19 21:07:13    56.475
Name: Spread, dtype: float64

它会持续很长时间(几个月到几年),所以每天都有很多观察。我想要做的是,我每天都想检索最接近特定时间的时间序列观察,比如 16:00。

到目前为止我的方法是

eodsearch = pd.DataFrame(df['Date'] + datetime.timedelta(hours=16))

eod = df.iloc[df.index.get_loc(eodsearch['Date'] ,method='nearest')]

目前给我一个错误

"Cannot convert input [Time Date, dtype: datetime64[ns]] of type <class 'pandas.core.series.Series'> to Timestamp 

此外,我看到 get_loc 也接受了 tolerance 作为输入,所以如果我可以将 tolerance 设置为 30 分钟,那也很好。

关于我的代码为何失败或如何修复它的任何建议?

最佳答案

准备数据:

from pandas.tseries.offsets import Hour

df.sort_index(inplace=True)  # Sort indices of original DF if not in sorted order
# Create a lookup dataframe whose index is offsetted by 16 hours
d = pd.DataFrame(dict(Time=pd.unique(df.index.date) + Hour(16)))

(i):使用 reindex它支持观察的双向查找:(双向兼容)

# Find values in original within +/- 30 minute interval of lookup 
df.reindex(d['Time'], method='nearest', tolerance=pd.Timedelta('30Min'))

enter image description here


(ii) :使用 merge_asof在识别原始 DF 中的唯一日期后:(向后兼容)

# Find values in original within 30 minute interval of lookup (backwards)
pd.merge_asof(d, df.reset_index(), on='Time', tolerance=pd.Timedelta('30Min'))

enter image description here


(iii):通过查询和重建索引获取 +/- 30 分钟带宽间隔的日期:

Index.get_loc 对输入的单个标签进行操作,因此不能将整个系列对象直接传递给它。

相反,DatetimeIndex.indexer_between_time它给出了索引的指定 start_timeend_time 内的所有行将更适合此目的。 (两个端点都包括在内)


# Tolerance of +/- 30 minutes from 16:00:00
df.iloc[df.index.indexer_between_time("15:30:00", "16:30:00")]

enter image description here

用于得出结果的数据:

idx = pd.date_range('1/1/2017', periods=200, freq='20T', name='Time')
np.random.seed(42)
df = pd.DataFrame(dict(observation=np.random.uniform(50,60,200)), idx)
# Shuffle indices
df = df.sample(frac=1., random_state=42)

信息:

df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 200 entries, 2017-01-02 07:40:00 to 2017-01-02 10:00:00
Data columns (total 1 columns):
observation    200 non-null float64
dtypes: float64(1)
memory usage: 3.1 KB

关于python - 为不规则间隔的数据找到最接近特定时间的每日观察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208206/

相关文章:

c# - ZedGraph - 如何从点到时间更改 X 轴?

python - 我想从我的数据框中获取原始价格

python - 为什么数据类不能在其类属性声明中具有可变默认值?

python-3.x - 显示多个满足特定条件的数据-PANDAS 中的问题

python - 仅对 pandas DataFrame 的一部分进行重新排序

c# - 考虑到夏令时,如何添加时间

r - 样本回归,x = 月,巨大的带宽

python - 将 pytz 导入 AWS lambda 函数

python - 为什么在 Windows 上启动新进程时 Python 的多处理模块会导入 __main__ ?

Python:使用正则表达式从 Pandas 系列中提取信息