numpy中的数据类型可以通过astype()方法进行转换,具体实现如下:

import numpy as np

a = np.array([1, 2, 3, 4])
print("原始数组:", a)
print("数据类型:", a.dtype)

# 转换为浮点数类型
b = a.astype(np.float32)
print("转换后数组:", b)
print("数据类型:", b.dtype)

# 转换为字符串类型
c = a.astype(np.str_)
print("转换后数组:", c)
print("数据类型:", c.dtype)

输出结果如下:

原始数组: [1 2 3 4]
数据类型: int32
转换后数组: [1. 2. 3. 4.]
数据类型: float32
转换后数组: ['1' '2' '3' '4']
数据类型: <U11

通过astype()方法,我们可以将原始数组转换为指定的数据类型,比如将整型数组转换为浮点型数组、字符串数组等。需要注意的是,转换后的数组是一个新的数组,原始数组并不会受到影响。

numpy 数据类型转换

原文地址: https://www.cveoy.top/t/topic/qLk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录