Issue
I'm trying to convert a column of my pandas dataframe from datetime['ns'] to datetime['us'].
I've tried using astype
but the column type doesn't seem to change. I need the type of the column itself to update due to some downstream libraries checking for a specific column type.
>> data[column].dtype.name
'datetime64[ns]'
>> data[column] = data[column].astype('datetime64[us]')
>> data[column].dtype.name
'datetime64[ns]'
Solution
I can reproduce, the behaviour you describe, in 1.5.3
.
So, you're most likely using a similar version or at least older than (2.0.0
). Why ?
Backwards incompatible API changes :
In past versions, when constructing a Series or DataFrame and passing a
datetime64
ortimedelta64
dtype with unsupported resolution (i.e. anything other than "ns"), pandas would silently replace the given dtype with its nanosecond analogue.
To get your cast work, you need to update your pandas' version :
pip install pandas==2.0.0
# or pip install -U pandas # latest
Minimal Reproducible Example :
import pandas as pd # >= 2.0.0
data = pd.DataFrame({"dt": pd.date_range("20240101", freq="T", periods=3)})
data["dt"].dtype.name # 'datetime64[ns]'
data["dt"].astype("datetime64[us]").dtype.name # 'datetime64[us]' <<
Answered By - Timeless
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.