本文将告诉你什么是NumPy的Ndarray,如何创建和操作Ndarray对象,并附有实例。
1.什么是NDarray
- NumPy定义了一个n维数组对象,被称为Ndarray对象。
- 它是一个由一系列相同类型的元素组成的数组集合。
- 数组中的每个元素都占据了一个相同大小的内存块。
- 你可以通过索引或分片获得数组中的每个元素。
- Ndarray 对象采用了数组的索引机制,将数组中的每个元素映射到内存块中,并按照一定的布局排列内存块。
- 有两种常见的布局方式,按行或按列。
- Ndarray 对象有一个 dtype 属性,描述元素的数据类型。
2.如何创建NDarray对象
-
我们可以通过NumPy的内置函数array()创建Ndarray对象,其语法格式如下:
numpy.array(object, dtype = None, copy = True, order = None,ndmin = 0) object: Represents an array sequence. dtype: Optional parameter that allows you to change the data type of the array. copy: Optional parameter indicating whether the array can be copied. The default is true. order: Memory layout options for creating arrays, there are three optional values: C (row sequence) / F (column sequence) / a (default). ndim: Specifies the dimension of the array. -
下面是创建Ndarray对象的例子
-
创建一个一维的ndarray
>>> import numpy >>> # create the ndarray object with the provided list object. >>> x = numpy.array(['numpy','pandas','matplotlib']) >>> >>> print(x) ['numpy' 'pandas' 'matplotlib'] >>> >>> print(type(x)) <class 'numpy.ndarray'> -
创建多维的ndarray
import numpy >>> y = numpy.array([['python', 'javascript', 'java'],['Linux','macOS','Windows']]) >>> >>> print(y) [['python' 'javascript' 'java'] ['Linux' 'macOS' 'Windows']] -
你可以通过设置dtype 属性值来改变数组元素的数据类型。
>>> import numpy # change the numpy array's element data type to string. >>> z = numpy.array([1,3,5,7,9],dtype="str") >>> # the number element in the array has been changed to string. >>> print(z) ['1' '3' '5' '7' '9']
3.如何查看NDArray的尺寸
-
通过Ndarray的ndim属性,你可以查看Ndarray的尺寸
>>> import numpy as np # create a 2 dimensional array. >>> ndarr = np.array([['a', 'b', 'c'], [1, 2, 3], ['python', 'javascript', 'java']]) >>> # print out the above ndarray >>> print(ndarr) [['a' 'b' 'c'] ['1' '2' '3'] ['python' 'javascript' 'java']] >>> >>> # get the ndarr object's dimensions by it's ndim attribute. >>> print(ndarr.ndim) 2 -
你也可以使用ndmin参数来创建不同尺寸的Ndarray。
>>> import numpy as np >>> # specify the ndarray dimension when call the arrary method. >>> a = np.array(['python', 'javascript', 'java'], ndmin = 3) >>> # print out the ndarray object. >>> print(a) [[['python' 'javascript' 'java']]] >>> # print out the ndarrary object's dimension. >>> print(a.ndim) 3
4.如何改变NDArray的尺寸
-
数组的形状指的是多维数组的行和列的数量。
-
改变数组的维度就是重塑数组的形状,例如,将一个2行数组([ [1,2,3], [4,5,6] ] )改为3行数组([ [1, 2], [3,4], [5.6] ] )。
-
Numpy模块提供了reshape()函数,它可以改变多维数组的行数和列数,达到改变NDdarray维度的目的。
-
reshape()函数可以接受一个元组作为参数来指定新数组的行和列的数量。
-
下面是reshape()函数的例子:
>>> import numpy as np >>> >>> source_arr = np.array([['python','javascript'],['java','c#'],['PHP','android']]) >>> >>> print("Source ndarray: ",source_arr) Source ndarray: [['python' 'javascript'] ['java' 'c#'] ['PHP' 'android']] >>> >>> reshape_arr = source_arr.reshape(2,3) >>> >>> print("Reshaped ndarray: ",reshape_arr) Reshaped ndarray: [['python' 'javascript' 'java'] ['c#' 'PHP' 'android']] >>> >>> print(source_arr.ndim) 2 >>> print(reshape_arr.ndim) 2