gpt4 book ai didi

python - Pandas 过滤 - 非索引列上的 between_time

转载 作者:太空狗 更新时间:2023-10-30 00:40:19 25 4
gpt4 key购买 nike

我需要过滤掉特定时间的数据。 DataFrame 函数 between_time 似乎是正确的方法,但是,它只适用于数据帧的索引列;但我需要原始格式的数据(例如,数据透视表希望日期时间列具有正确的名称,而不是索引)。

这意味着每个过滤器看起来像这样:

df.set_index(keys='my_datetime_field').between_time('8:00','21:00').reset_index()

这意味着每次运行这样的过滤器时都会有两次重建索引操作。

这是一个好的做法还是有更合适的方法来做同样的事情?

最佳答案

创建一个 DatetimeIndex,但将其存储在一个变量中,而不是 DataFrame。然后调用它的 indexer_between_time 方法。这将返回一个整数数组,然后可用于使用 ilocdf 中选择行:

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')]

关于python - Pandas 过滤 - 非索引列上的 between_time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28065284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com