You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中基于日期创建分类列:代码错误排查与修正

问题:基于自定义日期区间创建分类变量

给定数据

# importing libraries
import numpy as np
import pandas as pd 

# create data table
df = pd.DataFrame({
    'date': ['1/7/2020 19:09','11/18/2019 20:23','5/19/2023 14:55','9/11/2019 17:14']}) 

分类规则

Term Type日期范围
Summer3月23日 - 7月6日
Fall7月7日 - 10月23日
Spring10月24日 - 次年3月22日

我的尝试

我先提取月份和日期,再用np.where创建条件列,但输出全为"Fall",不符合预期:

# extracting month and day
df['month'] = pd.to_datetime(df["date"], format= date_format).dt.month
df['day']  = pd.to_datetime(df["date"], format= date_format).dt.day

# use np.where to create a conditional column
df['term_type'] = np.where((df['month']>=3) & (df['month']<6) & (df['day']<=6) & (df['day']>=23),'summer',
                    np.where((df['month']>=10) & (df['month']<=3) & (df['day']>=22),'spring','fall'))

期望输出

# Desired output
df['desired_term_type'] = ['spring','spring','summer','fall']

错误排查与修正方案

错误点分析

  1. 日期格式参数缺失:pd.to_datetime中format=date_format未定义,需根据输入日期格式指定format='%m/%d/%Y %H:%M',否则可能导致日期解析错误。
  2. Summer条件逻辑矛盾:原条件(df['month']>=3) & (df['month']<6) & (df['day']<=6) & (df['day']>=23)无法成立,一个日期的天数不可能同时满足>=23和<=6,且未覆盖7月1日-6日的区间。
  3. Spring条件逻辑错误:(df['month']>=10) & (df['month']<=3)逻辑矛盾,月份不可能同时大于等于10且小于等于3,未拆分跨年度的两个区间(10月24日-12月31日、1-3月22日)。

修正代码

方法1:利用一年中的天数简化判断

这种方法更简洁,避免复杂的多条件嵌套:

import numpy as np
import pandas as pd 

df = pd.DataFrame({
    'date': ['1/7/2020 19:09','11/18/2019 20:23','5/19/2023 14:55','9/11/2019 17:14']}) 

# 转换为datetime格式并指定正确格式
df['datetime'] = pd.to_datetime(df['date'], format='%m/%d/%Y %H:%M')
# 提取一年中的第几天(1-366)
df['day_of_year'] = df['datetime'].dt.dayofyear

# 定义各学期对应的天数区间
conditions = [
    (df['day_of_year'] >= 82) & (df['day_of_year'] <= 187),  # 3月23日(第82天)-7月6日(第187天)
    (df['day_of_year'] >= 188) & (df['day_of_year'] <= 296), # 7月7日(第188天)-10月23日(第296天)
    (df['day_of_year'] >= 297) | (df['day_of_year'] <= 81)   # 10月24日(第297天)-次年3月22日(第81天)
]
choices = ['Summer', 'Fall', 'Spring']

df['term_type'] = np.select(conditions, choices)

# 输出结果
print(df[['date', 'term_type']])

方法2:修正月日判断逻辑

如果坚持使用月份和日期判断,需拆分区间条件:

import numpy as np
import pandas as pd 

df = pd.DataFrame({
    'date': ['1/7/2020 19:09','11/18/2019 20:23','5/19/2023 14:55','9/11/2019 17:14']}) 

# 转换为datetime并提取月、日
df['datetime'] = pd.to_datetime(df['date'], format='%m/%d/%Y %H:%M')
df['month'] = df['datetime'].dt.month
df['day'] = df['datetime'].dt.day

# 修正条件逻辑
df['term_type'] = np.where(
    # Summer:3月23日-7月6日
    ((df['month'] == 3) & (df['day'] >= 23)) | 
    ((df['month'] >=4) & (df['month'] <=6)) | 
    ((df['month'] ==7) & (df['day'] <=6)),
    'Summer',
    np.where(
        # Fall:7月7日-10月23日
        ((df['month'] ==7) & (df['day'] >=7)) | 
        ((df['month'] >=8) & (df['month'] <=9)) | 
        ((df['month'] ==10) & (df['day'] <=23)),
        'Fall',
        # Spring:剩余跨年度区间
        'Spring'
    )
)

# 输出结果
print(df[['date', 'term_type']])

结果验证

两种方法均会得到符合预期的输出:

dateterm_type
1/7/2020 19:09Spring
11/18/2019 20:23Spring
5/19/2023 14:55Summer
9/11/2019 17:14Fall

内容的提问来源于stack exchange,提问作者Minh Chau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:00:01