简体   繁体   English

将浮点值转换为 pandas dataframe 中的 timedelta 值

[英]Converting float values to timedelta values in a pandas dataframe

I want to convert certain columns in dataframe to timedelta values.我想将 dataframe 中的某些列转换为 timedelta 值。 In this example the columns 'day 1','day 2','day 3' need to be converted from float values to time delta values (in days).在此示例中,列 'day 1'、'day 2'、'day 3' 需要从浮点值转换为时间增量值(以天为单位)。

#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我尝试使用pd.to_timedelta() function 进行转换,但是 go 错误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我也尝试使用.apply()函数但没有运气

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?关于如何将 dataframe 中的指定列转换为一行的任何想法?

Using .apply worked for me.使用.apply对我有用。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM