如何在Python中仅比较DataFrame日期的mm-dd部分并生成季节列
解决步骤
首先纠正你拆分date和time列的错误:你写的循环会把最后一行的日期赋值给整个date列,完全不符合预期。直接用pandas的dt访问器就能高效完成拆分,不用循环:
# 正确拆分date和time列 df_prueba['date'] = df_prueba['Fecha_Tiem'].dt.date df_prueba['time'] = df_prueba['Fecha_Tiem'].dt.time
接下来有两种方法生成Season列,判断日期是否在05-13至07-18之间:
方法一:字符串格式比较
把日期转成mm-dd格式的字符串,直接进行区间比较:
import numpy as np # 生成mm-dd格式字符串列 df_prueba['mm-dd'] = df_prueba['Fecha_Tiem'].dt.strftime('%m-%d') # 判断区间并赋值Season列 df_prueba['Season'] = np.where( (df_prueba['mm-dd'] >= '05-13') & (df_prueba['mm-dd'] <= '07-18'), 'high', '' # 不在区间内的默认值,可根据需求修改 )
方法二:月份+日期逻辑判断
通过提取月份和日期进行逻辑判断,这种方式更严谨,避免字符串比较可能出现的边缘问题:
import numpy as np # 构建判断条件 condition = ( (df_prueba['Fecha_Tiem'].dt.month == 5) & (df_prueba['Fecha_Tiem'].dt.day >= 13) ) | ( df_prueba['Fecha_Tiem'].dt.month == 6 ) | ( (df_prueba['Fecha_Tiem'].dt.month == 7) & (df_prueba['Fecha_Tiem'].dt.day <= 18) ) # 生成Season列 df_prueba['Season'] = np.where(condition, 'high', '')
内容的提问来源于stack exchange,提问作者Martin Palacios
相关产品推荐
相关产品推荐

