【问题标题】:Why does to_datetime result in an error when not assigning to a column, but variable?为什么 to_datetime 在不分配给列而是变量时会导致错误?
【发布时间】:2026-02-09 05:15:02
【问题描述】:

我有以下代码:

example = {'date': ['01_September_2020_abdca', '01_September_2020_sfasd'],
          'user': ['a', 'b']}

example_df = pd.DataFrame(example)
test = example_df['date'].str.extract('([0-3][0-9]_[a-zA-Z]*_[0-9]{4})')
display(pd.to_datetime(test, format='%d_%B_%Y'))

但是,这会导致错误,即“AttributeError: 'int' object has no attribute 'lower'”。但是,如果我将代码更改为对列的赋值,那么它可以工作:

example = {'date': ['01_September_2020_abdca', '01_September_2020_sfasd'],
          'user': ['a', 'b']}

example_df = pd.DataFrame(example)
example_df['date_datetime'] = example_df['date'].str.extract('([0-3][0-9]_[a-zA-Z]*_[0-9]{4})')
display(pd.to_datetime(example_df['date_datetime'], format='%d_%B_%Y'))

谁能解释一下为什么这两段代码不相等?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    当您执行test = example_df['date'].str.extract('([0-3][0-9]_[a-zA-Z]*_[0-9]{4})') 时,test 将成为数据框。

    pd.to_datetime 需要一个数据框的列。

    来自pd.to_datetime docs

    arg int, float, str, datetime, list, tuple, 1-d array, Series DataFrame/dict-like 要转换为日期时间的对象。

    改为这样做:

    In [2670]: pd.to_datetime(test[0], format='%d_%B_%Y')
    Out[2670]: 
    0   2020-09-01
    1   2020-09-01
    

    当你做example_df['date_datetime'] = example_df['date'].str.extract('([0-3][0-9]_[a-zA-Z]*_[0-9]{4})')时,

    您正在通过 date_datetime 在数据框 example_df 中添加一列。

    然后您在列本身上运行pd.to_datetime。因此它有效。

    【讨论】:

      【解决方案2】:

      问题是:

      pd.to_datetime(test, format='%d_%B_%Y')
      

      因为test 是DataFrame,而pd.to_datetime 只接受Series/1D-array。不过这很好用:

      display(pd.to_datetime(test[0], format='%d_%B_%Y'))
      

      或者

      display(test.apply(pd.to_datetime, format='%d_%B_%Y'))
      

      【讨论】:

        最近更新 更多