pandas DatetimeIndex索引dtype:datetime64与Timestamp [英] Pandas DatetimeIndex indexing dtype: datetime64 vs Timestamp

查看:177
本文介绍了 pandas DatetimeIndex索引dtype:datetime64与Timestamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为熊猫的DatetimeIndex(具有dtype numpy datetime64 [ns])建立索引将返回以下任一值:

Indexing a pandas DatetimeIndex (with dtype numpy datetime64[ns]) returns either:


  • 另一个用于多个索引的DatetimeIndex

  • 单个索引的熊猫时间戳

令人困惑的部分是时间戳不等于np.datetime64,因此

The confusing part is that Timestamps do not equal np.datetime64, so that:

import numpy as np
import pandas as pd

a_datetimeindex = pd.date_range('1/1/2016', '1/2/2016', freq = 'D')
print np.in1d(a_datetimeindex[0], a_datetimeindex)

返回false。但是:

Returns false. But:

print np.in1d(a_datetimeindex[0:1], a_datetimeindex)
print np.in1d(np.datetime64(a_datetimeindex[0]), a_datetimeindex)

返回正确的结果。

我想这是因为np.datetime64 [ns]的精度达到了纳秒,但是时间戳被截断了?

I guess that is because np.datetime64[ns] has accuracy to the nanosecond, but the Timestamp is truncated?

我的问题是,是否有一种方法可以创建DatetimeIndex,使其始终索引到相同(或类似)数据类型?

My question is, is there a way to create the DatetimeIndex so that it always indexes to the same (or comparable) data type?

推荐答案

您正在使用numpy函数来处理熊猫类型。它们并不总是兼容的。

You are using numpy functions to manipulate pandas types. They are not always compatible.

函数 np.in1d 首先将其两个参数都转换为ndarrays。 DatetimeIndex 具有内置转换,并返回dtype np.datetime64 的数组(它是 DatetimIndex.values )。但是 Timestamp 没有这种功能,也不会转换。

The function np.in1d first converts its both arguments to ndarrays. A DatetimeIndex has a built-in conversion and an array of dtype np.datetime64 is returned (it's DatetimIndex.values). But a Timestamp doesn't have such a facility and it's not converted.

相反,您可以使用例如中的python关键字(最自然的方式):

Instead, you can use for example a python keyword in (the most natural way):

a_datetimeindex[0] in a_datetimeindex

Index.isin 元素集合的方法

a_datetimeindex.isin(a_list_or_index)

如果要使用 np.in1d ,请将两个参数显式转换为numpy类型。或在基础numpy数组上调用它:

If you want to use np.in1d, explicitly convert both arguments to numpy types. Or call it on the underlying numpy arrays:

np.in1d(a_datetimeindex.values[0], a_datetimeindex.values)

或者,使用 np.in1d 可能是安全的并具有两个相同类型的集合:

Alternatively, it's probably safe to use np.in1d with two collections of the same type:

np.in1d(a_datetimeindex, another_datetimeindex)

甚至

np.in1d(a_datetimeindex[[0]], a_datetimeindex)

这篇关于 pandas DatetimeIndex索引dtype:datetime64与Timestamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆