I have a column in a dataframe that has datatype [timedelta64[ns]]. I'm trying to convert it to a float.
This is a sample table:
ColA
227 days 00:00:00.000000000
316 days 00:00:00.000000000
226 days 00:00:00.000000000
153 days 00:00:00.000000000
Below is my desired table with datatype as float:
ColA
227
316
226
153
This is the code I tried:
df_EVENT5_24['ColA'] = df_EVENT5_24['ColA'].astype(float)
This is the error: TypeError: cannot astype a timedelta from [timedelta64[ns]] to [float64]
您可以使用apply
和lambda
来访问属性days
( https://pandas.pydata.org/pandas-docs/stable/timedeltas.html ):
df_EVENT5_24['ColA'] = df_EVENT5_24.apply(lambda row: row.ColA.days, axis=1)
We can use the dt.days attribute. Example ColA is the name of your timedelta Series.
ColA = ColA.dt.days
To convert into a float, you need either df.astype
ColA = ColA.astype(float)
***ColA = ColA.dt.days.astype(float)***
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.