简体   繁体   English

如何在 pandas 表的时间间隔内获取具有 DatetimeIndex 的行?

[英]How to get rows having DatetimeIndex within time interval in pandas table?

I am using this method:我正在使用这种方法:

df = pd.DataFrame({'date': [datetime(2021, 11, 1, 13, 30), datetime(2021, 11, 2, 13, 31), datetime(2021, 11, 3, 13, 32), datetime(2021, 11, 1, 13, 33)],
                    'value': [1, 2, 3, 5]})
df = df.set_index('date')
df = df.loc[
  (df.index.time >= datetime.strptime("13:30", '%H:%M').time()) & \
  (df.index.time < datetime.strptime("13:32", '%H:%M').time())]

Is there any better way?有没有更好的办法?

I tried to use between() :我尝试使用between()

df = df.loc[
  df.index.time.between(
    datetime.strptime("13:30", '%H:%M').time(),
    datetime.strptime("13:32", '%H:%M').time())]

It generates an error:它会产生一个错误:

'numpy.ndarray' object has no attribute 'between'

And I didn't manage to find an appropriate numpy function.而且我没能找到合适的numpy function。

Use DataFrame.between_time :使用DataFrame.between_time

print (df.between_time('13:30','13:32'))
                     value
date                      
2021-11-01 13:30:00      1
2021-11-02 13:31:00      2
2021-11-03 13:32:00      3

Alternative would be替代方案是

df['date'] =pd.to_datetime(df['date'])
df[df['date'].dt.strftime("%H:%M").between('13:30','13:32')]

     

                 date  value
0 2021-11-01 13:30:00      1
1 2021-11-02 13:31:00      2
2 2021-11-03 13:32:00      3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取熊猫DateTimeIndex中的datetime索引? - How to get index of datetime within a pandas DateTimeIndex? 熊猫获得组内的平均时间间隔 - Pandas get average time interval within groups 获取时间戳在特定滑动 window 时间间隔 pandas (时间序列)内的行 - Get rows whose timestamps are within specific sliding window time interval pandas (Time Series) Pandas 从时间间隔内最后 N 行的第二个 dataframe 获取平均值 - Pandas get average from second dataframe of the last N rows within time interval 使用 pandas 的 datetimeindex 在特定日期按分钟和小时提取时间间隔 - Extracting time interval by minute and hour in a particular day using datetimeindex of pandas 计数 Pandas Dataframe 中时间间隔内的行数 - Count Number of Rows within Time Interval in Pandas Dataframe 如何获取Pandas中某列的时间间隔 - How To Get The Time Interval of a Column in Pandas 如何确定两个熊猫系列是否在给定的时间间隔内 - How to determine if two pandas Series are within a given time interval 以自定义间隔重新采样 Pandas 时间序列并获得一年内的间隔号 - Resample Pandas time series at custom interval and get interval number within a year 获取 pandas dataframe 中 datetimeindex 的时差并重新索引 - get the time difference in datetimeindex in pandas dataframe and re-index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM