如何在DataFrame中访问datetime属性并实现无循环的np.where筛选?
解决方法
你遇到的错误核心原因是:Pandas的DateTime列是Series对象,不能直接调用datetime的属性/方法,必须通过**.dt访问器**来获取这些时间属性;另外多个布尔条件组合时要使用&而非and(and不支持Series级别的向量运算),同时注意大部分时间属性是属性而非方法,不需要加括号(比如.dt.minute,不是.minute())。
修正后的代码如下:
import numpy as np import pandas as pd # 先确保DateTime列是datetime类型(如果原始数据是字符串格式的话) price_df_lower_interval['DateTime'] = pd.to_datetime(price_df_lower_interval['DateTime']) if interval_higher_str == 'seconds': occurances = np.where(price_df_lower_interval['DateTime'].dt.second == interval_higher) elif interval_higher_str == 'minutes': occurances = np.where( (price_df_lower_interval['DateTime'].dt.minute == interval_higher) & (price_df_lower_interval['DateTime'].dt.second == 0) ) elif interval_higher_str == 'hours': occurances = np.where( (price_df_lower_interval['DateTime'].dt.hour == interval_higher) & (price_df_lower_interval['DateTime'].dt.minute == 0) & (price_df_lower_interval['DateTime'].dt.second == 0) ) elif interval_higher_str == 'day': occurances = np.where( (price_df_lower_interval['DateTime'].dt.hour == trade_start_hour) & (price_df_lower_interval['DateTime'].dt.minute == 0) & (price_df_lower_interval['DateTime'].dt.second == 0) ) elif interval_higher_str == 'week': occurances = np.where( (price_df_lower_interval['DateTime'].dt.weekday() == 0) & (price_df_lower_interval['DateTime'].dt.hour == trade_start_hour) & (price_df_lower_interval['DateTime'].dt.minute == trade_start_minute) & (price_df_lower_interval['DateTime'].dt.second == 0) ) elif interval_higher_str == 'month': occurances = np.where( (price_df_lower_interval['DateTime'].dt.day == 1) & (price_df_lower_interval['DateTime'].dt.hour == trade_start_hour) & (price_df_lower_interval['DateTime'].dt.minute == trade_start_minute) & (price_df_lower_interval['DateTime'].dt.second == 0) ) elif interval_higher_str == 'year': occurances = np.where( (price_df_lower_interval['DateTime'].dt.month == 1) & (price_df_lower_interval['DateTime'].dt.day == 1) & (price_df_lower_interval['DateTime'].dt.hour == trade_start_hour) & (price_df_lower_interval['DateTime'].dt.minute == trade_start_minute) & (price_df_lower_interval['DateTime'].dt.second == 0) )
关键改动说明:
- 所有时间属性调用前添加
.dt访问器,这是Pandas专门用于Series级datetime操作的入口 - 区分属性和方法:
second/minute/hour/day/month是属性,不需要加括号;weekday()是方法,需要保留括号 - 多条件组合用
&替代and,且每个条件用括号包裹,避免运算优先级错误 - 先转换DateTime列为datetime类型,确保后续操作能正常调用
.dt访问器
这种方式属于Pandas原生的向量运算,完全不需要循环,效率和原生操作一致,符合你的需求。
内容的提问来源于stack exchange,提问作者Jakub Szurlej
相关产品推荐
相关产品推荐

