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

Python datetime列拆分工具函数报错求助:NameError问题

Fixing the NameError & Optimizing Your Datetime Column Splitting Function

Hey there! Let's break down what's going wrong and how to fix it, plus make your function even better.

First: Fixing the NameError

The error you're seeing is super straightforward—when you called datetime_to_cols(train, dateCreated), you passed dateCreated as a bare name instead of a string. Python interprets bare names as variables, but you never defined a variable called dateCreated (it's just the name of your DataFrame column).

The fix is simple: wrap the column name in quotes

datetime_to_cols(train, 'dateCreated')

Second: Optimizing Your Function

Your core logic works, but we can make the function cleaner, more robust, and easier to maintain. Here's an improved version:

import pandas as pd

def datetime_to_cols(df, col_to_convert):
    # Check if the target column exists in the DataFrame
    if col_to_convert not in df.columns:
        raise ValueError(f"Oops! Column '{col_to_convert}' doesn't exist in your DataFrame.")
    
    # Verify the column is actually a datetime type
    if not pd.api.types.is_datetime64_any_dtype(df[col_to_convert]):
        raise TypeError(f"Column '{col_to_convert}' isn't a datetime type. Convert it first with pd.to_datetime(df['{col_to_convert}'])!")
    
    # Define the time components we want to extract
    time_parts = [('year', 'year'), ('month', 'month'), ('day', 'day'),
                  ('hour', 'hour'), ('minute', 'minute'), ('second', 'second')]
    
    # Loop through each component to create new columns
    for part_name, dt_attr in time_parts:
        # Use underscores in new column names for better readability (e.g., dateCreated_year)
        new_col = f"{col_to_convert}_{part_name}"
        df[new_col] = df[col_to_convert].dt.__getattribute__(dt_attr)
    
    return df  # Optional: return the modified DataFrame for method chaining

Key improvements here:

  • Error checking: We add checks to make sure the column exists and is a datetime type, so you get clear, actionable error messages instead of confusing crashes later.
  • DRY (Don't Repeat Yourself) code: Instead of writing the same line 6 times, we use a loop. If you ever want to add more time components (like weekday or quarter), just add a tuple to the time_parts list.
  • Readable column names: Using underscores (e.g., dateCreated_year) makes the new columns easier to read than dateCreatedyear. If you prefer your original naming style, just change f"{col_to_convert}_{part_name}" to f"{col_to_convert}{part_name}".

One More Thing: Ensure Your Column is Datetime Type

If you haven't already converted dateCreated to a datetime type, run this first:

train['dateCreated'] = pd.to_datetime(train['dateCreated'])

That should get everything working smoothly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:22:42