本文共 2221 字,大约阅读时间需要 7 分钟。
import numpy as np
在此引入一次,下面直接使用 np
x = np.array([1, 2, 3, 4, 5])print('x = ', x) # x = [1 2 3 4 5]
.shape
属性x = np.array([1, 2, 3, 4, 5])print('x has dimensions:', x.shape) # x has dimensions: (5,)print(type(x)) # class 'numpy.ndarray'print('The elements in x are of type:', x.dtype) # The elements in x are of type: int64
说明:
shape
属性返回了元组 (5,)
,告诉我们 x
的秩为 1(即 x 只有一个维度),并且有 5 个元素。type()
函数告诉我们 x
的确是 NumPy ndarray
。.dtype
属性告诉我们 x
的元素作为有符号 64 位整数存储在内存中。x = np.array([1, 2, 'World']) print('The elements in x are of type:', x.dtype) # The elements in x are of type: U21
Y = np.array([[1,2,3],[4,5,6],[7,8,9], [10,11,12]])print('Y has dimensions:', Y.shape) # Y has dimensions: (4, 3)print('Y has a total of', Y.size, 'elements') # Y has a total of 12 elements Y is an object of type: class 'numpy.ndarray'print('The elements in Y are of type:', Y.dtype) # The elements in Y are of type: int64
.shape
属性返回元组 (4,3),告诉我们 Y 的秩为 2,有 4 行 3 列。.size
属性告诉我们 Y 共有 12 个元素。x = np.array([1,2,3])y = np.array([1.0,2.0,3.0])z = np.array([1, 2.5, 4])print(x.dtype) # int64print(y.dtype) # float64print(z.dtype) # float64
说明:
x = np.array([1.5, 2.2, 3.7, 4.0, 5.9], dtype = np.int64)print()print('x = ', x) # x = [1 2 3 4 5]print()print('The elements in x are of type:', x.dtype) # The elements in x are of type: int64
x = np.array([1, 2, 3, 4, 5])# 将 x ndarray 保存到叫做 my_array.npy 的文件中np.save('my_array', x) # 使用 load() 函数将保存的 ndarray 加载到变量中y = np.load('my_array.npy')print()print('y = ', y) # y = [1 2 3 4 5]print()print('y is an object of type:', type(y)) # y is an object of type: class 'numpy.ndarray' print()print('The elements in y are of type:', y.dtype) # The elements in y are of type: int64
注意:
.npy
,否则将出错。转载地址:http://izwei.baihongyu.com/