pandas to_timedelta 函数似乎将数据转换为 0
pandas to_timedelta function seems to convert data to 0
这对我一直有效,但从几天前开始,我得到了奇怪的结果。
my_list = [1,2,3,4,5]
my_series = pd.Series(my_list)
print pd.to_timedelta(my_series)
这只是 returns
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
谁能告诉我这是怎么回事?
编辑:
在我的实际代码中,我使用
将我的(即将成为 timedelta)列更改为整数
df['col'].astype(int, inplace = True)
在调用 to_timedelta 函数之前。我真的应该一直在做
new_col = pd.to_numeric(df['col'])
然后在 new_col 上调用 to_timedelta。也许有人可以阐明为什么会这样。
to_timedelta
的默认单位是'ns',请参考文档或函数原型:
def to_timedelta(arg, unit='ns', box=True, errors='raise', coerce=None):
所以您刚刚生成了 1 到 5 纳秒的增量,并且显示没有那么深。
您可能选择了错误的单位,将 unit='something useful for you' 传递给函数。
编辑以解释更多 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
这对我一直有效,但从几天前开始,我得到了奇怪的结果。
my_list = [1,2,3,4,5]
my_series = pd.Series(my_list)
print pd.to_timedelta(my_series)
这只是 returns
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
谁能告诉我这是怎么回事?
编辑: 在我的实际代码中,我使用
将我的(即将成为 timedelta)列更改为整数df['col'].astype(int, inplace = True)
在调用 to_timedelta 函数之前。我真的应该一直在做
new_col = pd.to_numeric(df['col'])
然后在 new_col 上调用 to_timedelta。也许有人可以阐明为什么会这样。
to_timedelta
的默认单位是'ns',请参考文档或函数原型:
def to_timedelta(arg, unit='ns', box=True, errors='raise', coerce=None):
所以您刚刚生成了 1 到 5 纳秒的增量,并且显示没有那么深。
您可能选择了错误的单位,将 unit='something useful for you' 传递给函数。
编辑以解释更多 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