Python 为什么在不指定列而指定变量时,to_datetime会导致错误?
我有以下代码:Python 为什么在不指定列而指定变量时,to_datetime会导致错误?,python,pandas,Python,Pandas,我有以下代码: 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,
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'))
有人能给我解释一下为什么这两段代码不相等吗?当你做
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数组、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\u datetime']=example_df['date'].str.extract('([0-3][0-9].[a-zA-Z]*.[u[0-9]{4})
您正在数据框example\u df
中通过date\u datetime
添加一列
然后在列本身上运行
pd.to_datetime
。因此它是有效的。当您执行测试=示例_df['date'].str.extract('([0-3][0-9].[a-zA-Z]*.[u[0-9]{4})
时,测试成为数据帧
pd.to_datetime
需要数据帧的列
发件人:
arg int、float、str、datetime、list、tuple、1-d数组、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\u datetime']=example_df['date'].str.extract('([0-3][0-9].[a-zA-Z]*.[u[0-9]{4})
您正在数据框example\u df
中通过date\u datetime
添加一列
然后在列本身上运行pd.to_datetime
。因此它是有效的。问题是:
pd.to_datetime(test, format='%d_%B_%Y')
因为test
是数据帧,而pd.to\u datetime
只接受Series/1D数组。但这很好:
display(pd.to_datetime(test[0], format='%d_%B_%Y'))
或
问题是:
pd.to_datetime(test, format='%d_%B_%Y')
因为test
是数据帧,而pd.to\u datetime
只接受Series/1D数组。但这很好:
display(pd.to_datetime(test[0], format='%d_%B_%Y'))
或