pandas 将字符串转换为python日期时间时出错

bxgwgixi  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(111)

下面是代码

import pandas as pd
pd.to_datetime(pd.DataFrame(['12/4/1982']))

字符串
然而,有了这个,我得到以下错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 1053, in to_datetime
    result = _assemble_from_unit_mappings(arg, errors, utc)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 1161, in _assemble_from_unit_mappings
    unit = {k: f(k) for k in arg.keys()}
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 1161, in <dictcomp>
    unit = {k: f(k) for k in arg.keys()}
               ^^^^
  File "/usr/local/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 1156, in f
    if value.lower() in _unit_map:
       ^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'lower'


你能帮我弄明白我的代码有什么问题吗?

yeotifhr

yeotifhr1#

您将整个框架提供给pd.to_datetime。在本例中(来自文档):
.如果提供了DataFrame,则该方法至少需要以下列:“year”、“month”、“day”。列“year”必须以4位格式指定。
请尝试以下操作:

import pandas as pd

df = pd.DataFrame(["12/4/1982"])
df[0] = pd.to_datetime(df[0])

print(df)

字符串
印刷品:

0
0 1982-12-04

相关问题