我需要按特定小时过滤掉数据.DataFrame函数between_time似乎是正确的方法,但它只适用于数据帧的索引列; 但是我需要以原始格式存储数据(例如,数据透视表将期望datetime列具有正确的名称,而不是索引).
这意味着每个过滤器看起来像这样:
df.set_index(keys='my_datetime_field').between_time('8:00','21:00').reset_index()
Run Code Online (Sandbox Code Playgroud)
这意味着每次运行此类过滤器时都会进行两次重建索引操作.
这是一个很好的做法还是有更合适的方法来做同样的事情?
unu*_*tbu 10
创建一个DatetimeIndex,但将其存储在变量中,而不是存储在DataFrame中.然后调用它的indexer_between_time方法.这将返回一个整数数组,然后可以使用该数组来选择df使用的行iloc:
import pandas as pd
import numpy as np
N = 100
df = pd.DataFrame(
{'date': pd.date_range('2000-1-1', periods=N, freq='H'),
'value': np.random.random(N)})
index = pd.DatetimeIndex(df['date'])
df.iloc[index.indexer_between_time('8:00','21:00')]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1939 次 |
| 最近记录: |