简体   繁体   English

将pandas timedelta转换为int作为向量化操作

[英]pandas timedelta to int as a vectorized operation

I have a dataframe with a date column (not a datetime index). 我有一个带有日期列(不是日期时间索引)的数据框。 I want to create another columns whose value is today minus date from the date column. 我想创建另一个列,其值是日期列中的今天减去日期。 I can do this as a vectorized operation ts['days ago'] = dt.date.today() -ts['foo'] 我可以将其作为矢量化操作ts['days ago'] = dt.date.today() -ts['foo']

But this gives me a Timedelta object, while I want an int. 但这给了我一个Timedelta对象,而我想要一个int。 Timedelta has an attribute .days that returns me an int. Timedelta有一个属性.days返回我一个int。 But I cannot see how to vectorize this operation to make a "days ago as int" column as below, as the vector subtraction gives me a series, not a Timedelta. 但是我看不到如何对这个操作进行矢量化处理,以使它成为下面的“ days as int”列,因为矢量减法给了我一个序列,而不是Timedelta。

rng = pd.date_range('6/1/2016', periods=10, freq='D')
ts = pd.Series(rng,  index=range(10)).to_frame()
ts.columns = ['foo']
ts['days ago'] = dt.date.today() -ts['foo'] 
ts['days ago as int'] = "?"

print ts.ix[3]['days ago'].days
# doesn't work
ts['days ago as int'] = ts.ix[:]['days ago'].days
ts

.apply获取天数属性可以将您的天数作为ints

ts["days ago int "] = ts['days ago'].apply(lambda x:x.days)

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

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