Python pandas to_timedelta函数似乎将数据转换为0
这一直对我有效,但从几天前开始,我得到了奇怪的结果Python pandas to_timedelta函数似乎将数据转换为0,python,pandas,timedelta,Python,Pandas,Timedelta,这一直对我有效,但从几天前开始,我得到了奇怪的结果 my_list = [1,2,3,4,5] my_series = pd.Series(my_list) print pd.to_timedelta(my_series) 刚刚回来 0 00:00:00:000000 1 00:00:00:000000 2 00:00:00:000000 3 00:00:00:000000 4 00:00:00:000000 谁能告诉我发生了什么事 编辑: 在我的实际代码中,我
my_list = [1,2,3,4,5]
my_series = pd.Series(my_list)
print pd.to_timedelta(my_series)
刚刚回来
0 00:00:00:000000
1 00:00:00:000000
2 00:00:00:000000
3 00:00:00:000000
4 00:00:00:000000
谁能告诉我发生了什么事
编辑:
在我的实际代码中,我使用
df['col'].astype(int, inplace = True)
在调用to_timedelta函数之前。我真的应该这么做
new_col = pd.to_numeric(df['col'])
然后调用新列上的\u timedelta。也许有人可以解释为什么会出现这种情况。到\u timedelta的默认单位为“ns”,请参阅文档或函数原型:
def to_timedelta(arg, unit='ns', box=True, errors='raise', coerce=None):
因此,您只生成了1到5秒的delta,并且显示没有那么深
很可能您选择了错误的单位,将unit='something for your'传递给函数
编辑以解释更多OP评论
通过使用合适的装置,您可以得到您想要的:
pd.to_timedelta(my_series, unit='D')
Out[415]:
0 1 days
1 2 days
2 3 days
3 4 days
4 5 days
dtype: timedelta64[ns]
该系列中的对象类型仍然是timedelta[ns]
,这是对象的内部表示形式。括号中的ns提醒您,timedelta对象的精度可降到纳秒
如果我取第一个元素的原始内部值,我会发现纳秒:
pd.to_timedelta(my_series, unit='D')[0].delta
Out[425]: 86400000000000
事实上是这样的,为了让timedelta注册,最小值应该是1000this@EdChum:嗯,“显示”,而不是“寄存器”--它们仍然在那里,在
pd.to_timedelta(my_series).dt.纳秒中@DSM啊,是的,这是真的。我只是查看输出,没有考虑timedelta属性。实际上,我使用的是unit='D',但返回的值是dtype:timedelta64[ns]。@EdChum在回答中补充了解释