当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python NumPy asfarray方法用法及代码示例

Numpy 的asfarray(~) 将数组转换为float 类型。

参数

1. a | array-like

要对其执行该方法的数组。

2. dtype | strtype | optional

将输入数组转换为的浮点类型。如果输入数组的类型为 int ,则它将转换为 float64

返回值

float 类型的 Numpy 数组。

例子

转换为 float64

x = [1,2,3]
y = np.asfarray(x)
y.dtype



dtype('float64')

提醒一下,所有 int 都会转换为 float64

转换为 float32

我们需要指定dtype="float32"

x = [1,2,3]
y = np.asfarray(x, dtype="float32")
y.dtype



dtype('float32')

原始数组保持不变

请注意,原始数组保持不变,即:

x = np.array([1,2,3])
y = np.asfarray(x)
x.dtype



dtype('int64')

这里, y 的类型为 float ,但 x 的类型为 int

相关用法


注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 NumPy | asfarray method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。