Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float values to timedelta values in a pandas dataframe

I want to convert certain columns in dataframe to timedelta values. In this example the columns 'day 1','day 2','day 3' need to be converted from float values to time delta values (in days).

#trail dataframe
newdf = pd.DataFrame({'days 1' : [14.3], 'val 1' : [147], 'days 2' : [16.7],'val 2' : [148], 'days 3' : [17.7],'val 3' : [149]})

I tried to convert using the pd.to_timedelta() function, but go an error arg must be a string, timedelta, list, tuple, 1-d array, or Series

newdf[['days 1','days 2', 'days 3']] = pd.to_timedelta(newdf[['days 1','days 2','days 3']],unit = 'D') 

However, when I separated each column as so, the code worked fine.

newdf['days 1'] = pd.to_timedelta(newdf['days 1'],unit = 'D')
newdf['days 2'] = pd.to_timedelta(newdf['days 2'],unit = 'D')
newdf['days 3'] = pd.to_timedelta(newdf['days 3'],unit = 'D')

I also tried using the .apply() functions with no luck

newdf[['days 1','days 2','days 3']] = newdf.apply(pd.to_timedelta(arg = ['days 1','days 2','days 3'],unit = 'D'))

Any ideas on how to convert the specified columns in the dataframe in one line?

like image 762
imantha Avatar asked Oct 15 '25 04:10

imantha


1 Answers

Using .apply worked for me. You incorrectly put your columns as args.

newdf[['days 1','days 2', 'days 3']] = newdf[['days 1','days 2','days 3']].apply(pd.to_timedelta,unit = 'D')
like image 78
David Erickson Avatar answered Oct 16 '25 18:10

David Erickson