您的位置:首页 > 编程语言 > Python开发

numpy (1) ndarray

2018-01-24 16:22 169 查看
import numpy as np

#python 列表
list = [1, 2, 3]
print(list)
print(type(list))

#将列表转换为ndarray
a = np.array(list)
print(a)
print(type(a))

#直接修改ndarray的值
a[0] = 5
a[1] = 4
a[2] = 9
print(a)

#二维的ndarray
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b)
print(type(b))

#ndarray的shape:两行三列
print(b.shape)

#二维ndarray数据的访问:输出,修改第零行第一列的数据
print(b[0, 1])
b[0, 1] = 100
print(b)

#创建两行三列都是零的ndarray
c = np.zeros((2, 3))
print(c)

#创建两行三列都是1的ndarray
c = np.ones((2, 3))
print(c)

#创建两行三列都是8的ndarray
c = np.full((2, 3), 8)
print(c)

#创建4*4的对角矩阵
d = np.eye(4)
print(d)

#产生三行两列的随机数,范围在0~1
e = np.random.random((3, 2))
print(e)

#产生2*3*4维度的ndarray,其中的数值无法预知(本质上在内存开辟了2*3*4维度的数据空间,内存没有被初始化,因此内存的数值也无法预知)
f = np.empty((2, 3, 4))
print(f)
print(f.shape)

#生成0~14的数字,步长为1
g = np.arange(15)
print(g)
print(g.shape)

#dtype表示data type
arr = np.array([1, 2, 3])
print(arr.dtype)

#也可以直接指定数据类型
arr = np.array([1, 2, 3], dtype=np.float16)
print(arr.dtype)

#类型转换,将int类型数据的ndarray转换成float16数据类型
int_arr = np.array([1, 2, 3, 4, 5])
print(int_arr, int_arr.dtype)
float_arr = int_arr.astype(np.float16)
print(float_arr, float_arr.dtype)

#使用astype将float转换为int时小数部分被舍弃
float_arr = np.array([3.5, 2.3, 4.8, -2.2])
print(float_arr)
int_arr = float_arr.astype(np.int8)
print(int_arr, int_arr.dtype)

#使用astype将字符串转换成数组,如果失败抛出异常
str_arr = np.array(['1.24', '2.2', '15.9'], dtype=np.string_)
float_arr = str_arr.astype(dtype=np.float16)
print(float_arr)

#astype使用其它数组的数据类型作为参数
int_arr = np.arange(10)
float_arr = np.array([2.3, 4.6, 9.8])
print(float_arr.dtype, int_arr.dtype)
int_arr.astype(dtype=float_arr.dtype)
float_arr.astype(dtype=int_arr.dtype)
print(int_arr, float_arr.dtype)
print(float_arr, int_arr.dtype)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: