详解使用Python列表创建ndarray

本笔记整理自 udacity 课程,版权归 udacity 所有, 更多信息请访问 Udacity

引入

import numpy as np

在此引入一次,下面直接使用 np

简单的创建

x = np.array([1, 2, 3, 4, 5])
print('x = ', x) # x = [1 2 3 4 5]

一些实用的术语

  • 一维数组称之为秩为 1 的数组, N 维数组的秩为 N
  • 数组的形状是指每个维度的大小。例如,秩为 2 的数组的形状对应于数组的行数和列数.

ndarray中的 .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 位整数存储在内存中。

关于ndarray的数据类型

  • 与 Python 列表不同的是,ndarray 的所有元素都必须类型相同。
  • 如果向 np.array() 函数提供同时具有整数和字符串的 Python 列表,NumPy 会将所有元素解析为字符串。

     x = np.array([1, 2, 'World'])
     print('The elements in x are of type:', x.dtype) # The elements in x are of type: U21
    

创建秩为 2 的 ndarray

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 个元素。

创建具有浮点数和整数的 ndarray

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) # int64
print(y.dtype) # float64
print(z.dtype) # float64

说明:

  • 当我们创建同时包含浮点数和整数的 ndarray 时,NumPy 也会为其元素分配 float64 dtype。这叫做向上转型。
  • 因为 ndarray 的所有元素都必须类型相同,因此在这种情况下,NumPy 将 z 中的整数向上转型为浮点数,避免在进行数学计算时丢失精度。

创建指定 dtype 的 ndarray

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
  • NumPy 通过去除小数将浮点数转换成了整数。
  • 如果希望达到一定的计算精度来节省内存,则指定 ndarray 的数据类型很有用。

在NumPy中加载文件和读取文件

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,否则将出错。

猜你喜欢

转载自blog.csdn.net/tyro_java/article/details/81051118