Pandas 过滤 - between_time 在非索引列上
Pandas filtering - between_time on a non-index column
我需要过滤掉特定时段的数据。 DataFrame 函数 between_time 似乎是正确的方法,但是,它只适用于数据帧的索引列;但我需要原始格式的数据(例如,数据透视表希望日期时间列具有正确的名称,而不是索引)。
这意味着每个过滤器看起来像这样:
df.set_index(keys='my_datetime_field').between_time('8:00','21:00').reset_index()
这意味着每次这样的过滤器都有两次重建索引操作运行。
这是一个好的做法还是有更合适的方法来做同样的事情?
创建一个 DatetimeIndex
,但将其存储在变量中,而不是 DataFrame 中。
然后调用它的 indexer_between_time
方法。这个 returns 一个整数数组,然后可以使用 iloc
用于 df
中的 select 行:
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')]
我需要过滤掉特定时段的数据。 DataFrame 函数 between_time 似乎是正确的方法,但是,它只适用于数据帧的索引列;但我需要原始格式的数据(例如,数据透视表希望日期时间列具有正确的名称,而不是索引)。
这意味着每个过滤器看起来像这样:
df.set_index(keys='my_datetime_field').between_time('8:00','21:00').reset_index()
这意味着每次这样的过滤器都有两次重建索引操作运行。
这是一个好的做法还是有更合适的方法来做同样的事情?
创建一个 DatetimeIndex
,但将其存储在变量中,而不是 DataFrame 中。
然后调用它的 indexer_between_time
方法。这个 returns 一个整数数组,然后可以使用 iloc
用于 df
中的 select 行:
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')]