如何从DataFrame的DateTime类型索引提取月份数值?遇KeyError:'Date'
解决KeyError: 'Date'的问题
你遇到这个错误的核心原因是:monthly的DateTime类型数据是索引,不是名为'Date'的列,所以直接调用monthly['Date']会找不到对应的列。
下面是两种直接可行的解决方法:
方法一:直接从索引提取月份数值
因为你的索引是DatetimeIndex类型,直接通过索引的month属性提取即可:monthly['Month'] = monthly.index.month方法二:先将索引转为列再提取
如果需要把DateTime索引转为名为'Date'的列,再提取月份,可以先重置索引:# 将索引转为'Date'列 monthly = monthly.reset_index() # 提取月份 monthly['Month'] = pd.DatetimeIndex(monthly['Date']).month
额外补充:如果需要提取月份的英文名称(如"January"),可以使用month_name()方法:
monthly['Month_Name'] = monthly.index.month_name()
内容的提问来源于stack exchange,提问作者Mine
相关产品推荐
相关产品推荐

