I want to convert Timedelta to float

Asked

Viewed 379 times

-1

I have a Dataframe in which one of the columns is the time interval in days between the search from one row to another, the data of this column are in the Timedelta form, as in the example: Timedelta('61 days 00:00:00')

I need to convert this column to Float in order to operate it

I tried to convert as follows:

i = 1
ts= df_h['Intervalo Pesquisa'][i].total_seconds()
ts

That works perfectly and returns me a float, but when I put the function inside a for, it does not rotate:

td_list = []
for i in range (8410):
    ts= df_h['Intervalo Pesquisa'][i].total_seconds()
    td = ts/86400 #dividir total de segundos pelos segundos de um dia 
    td_list.append(td)

Returns me the following error:

AttributeError                            Traceback (most recent call last)
<ipython-input-88-99d7df4ff6da> in <module>()
  1 td_list = []
  2 for i in range (8410):
----> 3     ts= df_h['Intervalo Pesquisa'][i].total_seconds()
  4     td = ts/86400 #dividir total de segundos pelos segundos de um dia
  5     td_list.append(td)

AttributeError: 'int' object has no attribute 'total_seconds'

I don’t know why it’s not working.

I accept suggestions for other methods to convert Timedelta to Float

1 answer

0

First, if df_h['Intervalo Pesquisa'][1].total_seconds() throws the error 'int' object has no attribute 'total_seconds' is because in that column the values are of the type int. Usa df_h.dtypes to check the types and have to appear Intervalo Pesquisa timedelta64[ns].

Second, never use for, is very inefficient, use apply. A complete example:

import pandas as pd

dados = {'Intervalo Pesquisa': [pd.Timedelta('%d days 00:00:00' % i) for i in range(3)]}
df = pd.DataFrame(dados)

td_list = df['Intervalo Pesquisa'].apply(lambda x: x.total_seconds()/86400).tolist()
print(td_list)

The way out:

[0.0, 1.0, 2.0]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.