熊猫to_timedelta函数似乎将数据转换为0

bos*_*son 2 python timedelta pandas

这一直对我有用,但是从几天前开始,我得到了奇怪的结果。

my_list = [1,2,3,4,5]
my_series = pd.Series(my_list)
print pd.to_timedelta(my_series)
Run Code Online (Sandbox Code Playgroud)

刚刚返回

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
Run Code Online (Sandbox Code Playgroud)

谁能告诉我发生了什么事?

编辑:在我的实际代码中,我使用以下命令将我的(即将成为timedelta)列更改为整数

df['col'].astype(int, inplace = True)
Run Code Online (Sandbox Code Playgroud)

在调用to_timedelta函数之前。我真的应该一直在做

new_col = pd.to_numeric(df['col'])
Run Code Online (Sandbox Code Playgroud)

然后在new_col上调用to_timedelta。也许有人可以阐明为什么会这样。

Bou*_*oud 5

默认单位为to_timedelta“ ns”,请参考文档或函数原型:

def to_timedelta(arg, unit='ns', box=True, errors='raise', coerce=None):
Run Code Online (Sandbox Code Playgroud)

因此,您仅生成了1到5纳秒的增量,并且显示的深度没有那么深。

可能是您选择了错误的单位,将unit =“对您有用的东西”传递给函数。

编辑以解释更多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]
Run Code Online (Sandbox Code Playgroud)

该系列中的对象类型仍然是对象timedelta[ns]的内部表示。括号中的ns提醒您timedelta对象的精确度可降至纳秒。

如果我获取第一个元素的原始内部值,则会发现纳秒级:

pd.to_timedelta(my_series, unit='D')[0].delta
Out[425]: 86400000000000
Run Code Online (Sandbox Code Playgroud)