I want to convert Timedelta to float

-1

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

I need to convert this column to Float, so I can operate it

I tried converting as follows:

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

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

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)

I get 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 do not know why it's not working.

I accept suggestions for other methods to convert Timedelta to Float

    
asked by anonymous 23.10.2018 / 03:31

1 answer

0

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

Second, never use for , it 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 output:

[0.0, 1.0, 2.0]
    
29.10.2018 / 21:54