pandas.Index.to_numpy#

Index.to_numpy(dtype=None, copy=False, na_value=NoDefault.no_default, **kwargs)[源代码]#

表示此系列或索引中的值的NumPy ndarray。

参数
dtype字符串或umpy.dtype,可选

要传递到的数据类型 numpy.asarray()

copy布尔值,默认为False

是否确保返回值不是另一个数组上的视图。请注意 copy=False确保to_numpy() 是不复印的。更确切地说, copy=True 确保复制一份,即使不是绝对必要的。

na_value任何,可选

用于缺少值的值。缺省值取决于 dtype 以及数组的类型。

1.0.0 新版功能.

**kwargs

其他关键字传递给 to_numpy 基础数组的方法(用于扩展数组)。

1.0.0 新版功能.

退货
numpy.ndarray

参见

Series.array

获取存储在中的实际数据。

Index.array

获取存储在中的实际数据。

DataFrame.to_numpy

DataFrame采用了类似的方法。

注意事项

返回的数组在相等之前将是相同的(值等于 self 在返回的数组中将相等;不相等的值也是如此)。什么时候 self 包含Extension数组,则数据类型可能不同。例如,对于类别-dtype系列, to_numpy() 将返回一个NumPy数组,并且分类数据类型将丢失。

对于NumPy数据类型,这将是对此系列或索引中存储的实际数据的引用(假设 copy=False )。就地修改结果将修改存储在系列或索引中的数据(我们不建议这样做)。

For extension types, to_numpy() may require copying data and coercing the result to a NumPy type (possibly object), which may be expensive. When you need a no-copy reference to the underlying data, Series.array should be used instead.

此表列出了的不同数据类型和默认返回类型 to_numpy() 适用于Pandas内部的各种数据类型。

数据类型

数组类型

范畴 [T]

ndarray [T] (与输入相同的数据类型)

期间

ndarray [对象] (句号)

间隔

ndarray [对象] (间隔时间)

整型NA

ndarray [对象]

日期时间64 [ns]

日期时间64 [ns]

日期时间64 [NS,TZ]

ndarray [对象] (时间戳)

示例

>>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
>>> ser.to_numpy()
array(['a', 'b', 'a'], dtype=object)

指定 dtype 以控制如何表示支持日期时间的数据。使用 dtype=object 送回一群大Pandas Timestamp 对象,每个对象都具有正确的 tz

>>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> ser.to_numpy(dtype=object)
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'),
       Timestamp('2000-01-02 00:00:00+0100', tz='CET')],
      dtype=object)

dtype='datetime64[ns]' 返回本机DateTime64值的ndarray。这些值将转换为UTC,并删除时区信息。

>>> ser.to_numpy(dtype="datetime64[ns]")
... 
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],
      dtype='datetime64[ns]')