Issue
I have below code
import pandas as pd
pd.to_datetime(pd.DataFrame(['12/4/1982']))
However with this, I am getting below error
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'
Could you please help to understand what was wrong with my code?
Solution
You're supplying whole dataframe to pd.to_datetime
. In this case (from the documentation):
... If a DataFrame is provided, the method expects minimally the following columns: "year", "month", "day". The column “year” must be specified in 4-digit format.
Try this instead:
import pandas as pd
df = pd.DataFrame(["12/4/1982"])
df[0] = pd.to_datetime(df[0])
print(df)
Prints:
0
0 1982-12-04
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.