Skip to content

BUG: does not change column type when using .loc & to_datetime #53018

@shraik

Description

@shraik

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
df3=pd.DataFrame(['01/30/2023','01/30/2023','01/30/2023'],columns=['date'])
print(df3)
df3.loc[:,"date"] = pd.to_datetime(df3["date"], errors='coerce', utc=True)
print("------var1.loc------")
print(df3.dtypes)

print("------var2------")
df3["date"] = pd.to_datetime(df3["date"], errors='coerce', utc=True)
print(df3.dtypes)

Issue Description

In version 2.0.1, when using .loc, there will be no column type conversion.
In version 1.5.3, the column type always changed.

Output on version 2.0.1:
date
0 01/30/2023
1 01/30/2023
2 01/30/2023
------var1.loc------
date object
dtype: object
------var2------
date datetime64[ns, UTC]
dtype: object

Expected Behavior

As of version 1.5.3, the column type must always change to
datetime64[ns, UTC]

Installed Versions

INSTALLED VERSIONS

commit : 37ea63d
python : 3.11.3.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.20348
machine : AMD64
processor : Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : Russian_Russia.1251

pandas : 2.0.1
numpy : 1.24.3
pytz : 2023.2
dateutil : 2.8.2
setuptools : 67.7.2
pip : 23.1.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : 3.1.0
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 8.13.1
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.2
pandas_gbq : None
pyarrow : 11.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugDuplicate ReportDuplicate issue or pull requestNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions