为什么在不指定列而指定变量时,to_datetime会导致错误?

2024-10-01 15:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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’对象没有属性‘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'))

有人能解释一下为什么这两段代码不相等吗


Tags: 代码testdataframedfdatetimedateexampleextract
2条回答

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

pd.to_datetime需要数据帧的列

^{}

arg int, float, str, datetime, list, tuple, 1-d array, Series DataFrame/dict-like The object to convert to a datetime.

改为这样做:

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添加列

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

问题是:

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

因为test是数据帧,而pd.to_datetime只接受Series/1D数组。但这很好:

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

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

相关问题 更多 >

    热门问题