首页 > 解决方案 > Numpy 中 np.int64(x) 和 x.astype(np.int64) 的区别

问题描述

如果我有一个x要转换为特定数组的数组,dtype推荐的方法是x.astype(dtype). 但是,您似乎也可以dtype直接通过dtype(x). 这是来自 IPython 会话的示例:

In [1]: import numpy as np

In [2]: x = np.arange(12, dtype=float)

In [3]: x
Out[3]: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])

In [4]: x.dtype
Out[4]: dtype('float64')

In [5]: np.int64(x)
Out[5]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11], dtype=int64)

In [6]: x.astype(np.int64)
Out[6]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11], dtype=int64)

这两种方法有什么区别?该astype方法允许您控制复制、强制转换规则以及子类是否正常等内容。另一种方法实际上是做什么的?它是特定设置的别名吗?

标签: pythonarraysnumpy

解决方案


推荐阅读