Python DataFrame isocalendar()布尔条件在ISO年与公历年不一致时未达预期
问题:筛选2007年第一周数据却返回全年数据
我需要筛选出2007年第一周的数据,但设置的布尔条件却返回了全年数据,原代码如下:
# 示例数据 df1 = pd.DataFrame([1596., 1537., 1482., 1960., 1879., 1824.], index=['2007-01-01 00:00:00', '2007-01-01 01:00:00', '2007-01-01 02:00:00', '2007-12-31 21:00:00', '2007-12-31 22:00:00', '2007-12-31 23:00:00']) df1.index = pd.to_datetime(df1.index, format='%Y-%m-%d %H:%M:%S') # 尝试筛选2007年第一周数据并绘图 year_plot = 2007 year_data = df1[(df1.index.year == year_plot) & (df1.index.isocalendar().week == 1)] print(year_data) # 输出结果包含2007全年数据(示例输出省略部分行) # DAYTON_MW # Datetime # 2007-01-01 00:00:00 1596.0 # ... # 2007-12-31 23:00:00 1824.0 year_data.plot(figsize=(15, 5), title='Week Of Data') plt.show()
问题原因
原代码仅匹配公历年份和ISO周数,而2007年12月31日属于ISO 2008年的第1周,但它的公历年份是2007,因此被错误纳入筛选结果。
正确代码
通过同时匹配ISO年份和ISO周数,解决该问题:
df1[(df1.index.isocalendar().year == year_plot) & (df1.index.isocalendar().week == 1)]\ .plot(figsize=(15, 5), title='Week Of Data') # plt.savefig('oneweek.png') plt.show()
内容的提问来源于stack exchange,提问作者Mainland
相关产品推荐
相关产品推荐

