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?
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')
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.