Numpy如何使用N维数组(ndarray)?详细指南

2021年3月19日17:13:18 发表评论 705 次浏览

Numpy中的N维数组(ndarray)

Numpy中的Array是所有相同类型的元素(通常是数字)表, 由正整数元组索引。在Numpy中, 数组的维数称为数组的秩。给出每个方向的数组大小的整数元组称为数组的形状。 Numpy中的数组类称为ndarray。 Numpy数组中的元素可以使用方括号访问, 并且可以使用嵌套的Python列表进行初始化。

范例:

[[ 1, 2, 3], [ 4, 2, 5]]

Here, rank = 2 (as it is 2-dimensional or it has 2 axes)
First dimension(axis) length = 2, second dimension has length = 3
overall shape can be expressed as: (2, 3)
# Python program to demonstrate 
# basic array characteristics
import numpy as np

# Creating array object
arr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] )

# Printing type of arr object
print("Array is of type: ", type(arr))

# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)

# Printing shape of array
print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array
print("Size of array: ", arr.size)

# Printing type of elements in array
print("Array stores elements of type: ", arr.dtype)

输出:

Array is of type:  <class 'numpy.ndarray'>
No. of dimensions:  2
Shape of array:  (2, 3)
Size of array:  6
Array stores elements of type:  int64

数组创建

在NumPy中有多种创建数组的方法。

  • 例如, 你可以从常规Python创建数组listortuple使用Array功能。根据序列中元素的类型推导所得数组的类型。
  • 通常, 数组的元素最初是未知的, 但是其大小是已知的。因此, NumPy提供了几种函数来创建带有初始占位符内容。这些将增长阵列的必要性降到最低, 这是一项昂贵的操作。
    例如:np.zeros, np.ones, np.full, np.empty等。
  • 为了创建数字序列, NumPy提供了类似于range的函数, 该函数返回数组而不是列表。
  • 范围:返回给定间隔内的均匀间隔的值。步骤指定大小。
  • linspace:返回给定间隔内的均匀间隔的值。数没有。的元素被返回。
  • 重塑数组:我们可以用重塑重塑数组的方法。考虑一个形状为(a1, a2, a3, …, aN)的数组。我们可以重塑形状并将其转换为形状为(b1, b2, b3, …, bM)的另一个数组。唯一需要的条件是:
    a1 x a2 x a3…x aN = b1 x b2 x b3…x bM。 (即数组的原始大小保持不变。)
  • 展平数组:我们可以用展平获取数组副本的方法折叠成一维。它接受订购论据。默认值为" C"(对于行顺序较大的订单)。使用" F"表示列的主要订单。

注意:创建数组时可以显式定义数组的类型。

# Python program to demonstrate
# array creation techniques
import numpy as np

# Creating array from list with type float
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

# Creating array from tuple
b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

# Creating a 3X4 array with all zeros
c = np.zeros((3, 4))
print ("\nAn array initialized with all zeros:\n", c)

# Create a constant value array of complex type
d = np.full((3, 3), 6, dtype = 'complex')
print ("\nAn array initialized with all 6s." 
            "Array type is complex:\n", d)

输出:

Array created using passed list:
 [[ 1.  2.  4.]
 [ 5.  8.  7.]]

Array created using passed tuple:
 [1 3 2]

An array initialized with all zeros:
 [[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]

An array initialized with all 6s. Array type is complex:
 [[ 6.+0.j  6.+0.j  6.+0.j]
 [ 6.+0.j  6.+0.j  6.+0.j]
 [ 6.+0.j  6.+0.j  6.+0.j]]

数组索引

了解数组索引的基础对于分析和操作数组对象很重要。 NumPy提供了许多进行数组索引的方法。

  • 切片:就像python中的列表一样, 可以对NumPy数组进行切片。由于数组可以是多维的, 因此需要为数组的每个维度指定一个切片。
  • 整数数组索引:在此方法中, 将传递列表以为每个维度建立索引。完成了对应元素的一对一映射, 以构造一个新的任意数组。
  • 布尔数组索引:当我们要从满足条件的数组中选择元素时, 使用此方法。
# Python program to demonstrate
# indexing in numpy
import numpy as np

# An exemplar array
arr = np.array([[-1, 2, 0, 4], [4, -0.5, 6, 0], [2.6, 0, 7, 8], [3, -7, 4, 2.0]])

# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
                    "columns(0 and 2):\n", temp)

# Integer array indexing example
temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1), "
                                    "(3, 0):\n", temp)

# boolean array indexing example
cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)

输出:

Array with first 2 rows and alternatecolumns(0 and 2):
 [[-1.  0.]
 [ 4.  6.]]

Elements at indices (0, 3), (1, 2), (2, 1), (3, 0):
 [ 4.  6.  0.  3.]

Elements greater than 0:
 [ 2.   4.   4.   6.   2.6  7.   8.   3.   4.   2. ]

基本操作

NumPy中提供了内置算术函数的Plethora。

在单个阵列上的操作:

我们可以使用重载算术运算符对数组进行按元素运算以创建新数组。在+ =, -=, * =运算符的情况下, 将修改现有数组。

# Python program to demonstrate
# basic operations on single array
import numpy as np

a = np.array([1, 2, 5, 3])

# add 1 to every element
print ("Adding 1 to every element:", a+1)

# subtract 3 from each element
print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10
print ("Multiplying each element by 10:", a*10)

# square each element
print ("Squaring each element:", a**2)

# modify existing array
a *= 2
print ("Doubled each element of original array:", a)

# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)

输出:

Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 -1  2  0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1  4 25  9]
Doubled each element of original array: [ 2  4 10  6]

Original array:
 [[1 2 3]
 [3 4 5]
 [9 6 0]]
Transpose of array:
 [[1 3 9]
 [2 4 6]
 [3 5 0]]

一元运算符:

提供了许多一元运算作为一种方法

ndarray

类。其中包括求和, 最小值, 最大值等。通过设置轴参数, 也可以按行或按列应用这些功能。

# Python program to demonstrate
# unary operators in numpy
import numpy as np

arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]])

# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:", arr.max(axis = 1))

# minimum element of array
print ("Column-wise minimum elements:", arr.min(axis = 0))

# sum of array elements
print ("Sum of all array elements:", arr.sum())

# cumulative sum along each row
print ("Cumulative sum along each row:\n", arr.cumsum(axis = 1))

输出:

Largest element is: 9
Row-wise maximum elements: [6 7 9]
Column-wise minimum elements: [1 1 2]
Sum of all array elements: 38
Cumulative sum along each row:
[[ 1  6 12]
 [ 4 11 13]
 [ 3  4 13]]

二进制运算符:

这些操作逐个应用于数组, 并创建一个新数组。你可以使用所有基本的算术运算符, 例如+, -, /,

等等。如果为+ =, -=,

=运算符, 将修改现有数组。

# Python program to demonstrate
# binary operators in Numpy
import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[4, 3], [2, 1]])

# add arrays
print ("Array sum:\n", a + b)

# multiply arrays (elementwise multiplication)
print ("Array multiplication:\n", a*b)

# matrix multiplication
print ("Matrix multiplication:\n", a.dot(b))

输出如下:

Array sum:
[[5 5]
 [5 5]]
Array multiplication:
[[4 6]
 [6 4]]
Matrix multiplication:
[[ 8  5]
 [20 13]]

通用功能(ufunc):

NumPy提供了熟悉的数学函数, 例如sin, cos, exp等。这些函数还在数组上逐元素进行运算, 从而生成数组作为输出。

注意:上面我们使用重载运算符执行的所有操作都可以使用ufunc来完成, 例如np.add, np.subtract, np.multiply, np.divide, np.sum等。

# Python program to demonstrate
# universal functions in numpy
import numpy as np

# create an array of sine values
a = np.array([0, np.pi/2, np.pi])
print ("Sine values of array elements:", np.sin(a))

# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))

# square root of array values
print ("Square root of array elements:", np.sqrt(a))

输出如下:

Sine values of array elements: [  0.00000000e+00   1.00000000e+00   1.22464680e-16]
Exponent of array elements: [  1.           2.71828183   7.3890561   20.08553692]
Square root of array elements: [ 0.          1.          1.41421356  1.73205081]

数据类型

每个ndarray都有一个关联的数据类型(dtype)对象。此数据类型对象(dtype)通知我们有关数组的布局。这意味着它为我们提供了有关以下信息:

  • 数据类型(整数, 浮点数, Python对象等)
  • 数据大小(字节数)
  • 数据的字节顺序(小端或大端)
  • 如果数据类型是子数组, 则其形状和数据类型是什么。

a的值

ndarray

存储在缓冲区中, 可以将其视为连续的存储字节块。因此, 如何解释这些字节由dtype对象给出。

每个Numpy数组都是一个元素表(通常是数字), 所有元素都是相同类型的, 由正整数元组索引。每个ndarray都有一个关联的数据类型(dtype)对象。

此数据类型对象(dtype)提供有关数组布局的信息。 ndarray的值存储在缓冲区中, 缓冲区可以被视为连续的内存字节块, 可以由dtype对象解释。 Numpy提供了大量可用于构造数组的数字数据类型。

在创建数组时, Numpy会尝试猜测一个数据类型, 但是构造数组的函数通常还包含一个可选参数来显式指定该数据类型。

# Python Program to create a data type object
import numpy as np

# np.int16 is converted into a data type object.
print(np.dtype(np.int16))

输出如下:

int16
# Python Program to create a data type object 
# containing a 32 bit big-endian integer
import numpy as np

# i4 represents integer of size 4 byte
# > represents big-endian byte ordering and
# < represents little-endian encoding.
# dt is a dtype object
dt = np.dtype('>i4')

print("Byte order is:", dt.byteorder)

print("Size is:", dt.itemsize)

print("Data type is:", dt.name)

输出如下:

Byte order is: >
Size is: 4
Name of data type is: int32
木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: