如何在Python中创建含双条件的time_mask(时间范围+排除周末)
问题
需要绘制一段特定起止时间的数据,同时排除该时间段内的某个周末时段,如何创建包含这两条规则的time_mask?
已完成起止时间范围的time_mask代码,但无法添加排除周末时段的规则,尝试的代码无效,且后续绘图中该时段未被排除。
相关代码:
# create a time_mask start_date = '2022-06-30 15:26:00' end_date = '2022-07-11 15:30:00' weekend_end = '2022-07-08 14:30:00' weekend_start = '2022-07-11 09:50:00' time_mask = (df['Time'] > start_date) & (df['Time'] <= end_date) # use only this part of the dataframe as training data df1_train = df1.loc[time_mask]
尝试排除周末时段的无效代码:
time_mask = ((df['Time'] > start_date) & (df['Time'] <= end_date) & ((df['Time'] < weekend_start) or (df['Time'] > weekend_end)))
更新后的绘图代码(目标时段仍未被排除):
#%% Plot data fig, ax = plt.subplots() ax.plot(df['Time'], df1[Temp]) ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d %H:%M:%S')) fig.autofmt_xdate() plt.show() #%% Plot the data without empty values N = len(df['Time']) ind = np.arange(N) def format_date(x, pos=None): thisind = np.clip(int(x + 0.5), 0, N - 1) return df['Time'][thisind].strftime('%Y-%m-%d %H:%M:%S') fig, ax = plt.subplots() ax.plot(ind, df[Temp]) ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) ax.set_title("Without empty values") fig.autofmt_xdate() plt.show()
解决方案
1. 修正time_mask的逻辑错误
你用了Python的or运算符,但在Pandas布尔索引中必须使用按位或运算符|,or会尝试将整个布尔序列转为单个布尔值,直接导致逻辑失效。
另外注意你定义的weekend_start和weekend_end顺序:要排除的时段是weekend_end(2022-07-08)到weekend_start(2022-07-11)之间的部分,所以正确逻辑是保留**小于weekend_end或者大于weekend_start**的数据。同时建议将所有日期字符串转为Pandas的datetime类型,避免字符串比较的潜在问题。
修正后的time_mask代码:
import pandas as pd # 先确保Time列是datetime类型(若未转换) df['Time'] = pd.to_datetime(df['Time']) # 转换所有日期参数为datetime类型 start_date = pd.to_datetime('2022-06-30 15:26:00') end_date = pd.to_datetime('2022-07-11 15:30:00') weekend_end = pd.to_datetime('2022-07-08 14:30:00') weekend_start = pd.to_datetime('2022-07-11 09:50:00') # 正确的time_mask:总时间范围内,且不在目标周末时段内 time_mask = (df['Time'] > start_date) & (df['Time'] <= end_date) & \ ((df['Time'] < weekend_end) | (df['Time'] > weekend_start)) df1_train = df1.loc[time_mask]
2. 修正绘图代码的数据源错误
你当前绘图用的是原始的df和df1,而非筛选后的df1_train,所以排除的时段不会在图中体现。需要将绘图数据源替换为筛选后的数据集:
修正后的绘图代码:
import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as ticker import numpy as np #%% 绘制筛选后的数据 fig, ax = plt.subplots() ax.plot(df1_train['Time'], df1_train[Temp]) # 改用df1_train作为数据源 ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) fig.autofmt_xdate() plt.show() #%% 绘制无空值的筛选后数据 N = len(df1_train['Time']) ind = np.arange(N) def format_date(x, pos=None): thisind = np.clip(int(x + 0.5), 0, N - 1) return df1_train['Time'].iloc[thisind].strftime('%Y-%m-%d %H:%M:%S') # 用iloc避免索引错位 fig, ax = plt.subplots() ax.plot(ind, df1_train[Temp]) # 改用df1_train作为数据源 ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) ax.set_title("无空值数据(已排除目标周末时段)") fig.autofmt_xdate() plt.show()
额外注意事项
- 若
df1和df的索引未对齐,df1.loc[time_mask]可能筛选错误,建议确保两者索引一致,或直接对df1的Time列应用相同掩码。
内容的提问来源于stack exchange,提问作者ecc98
相关产品推荐
相关产品推荐

