首页 > 代码库 > numpy教程:数组操作
numpy教程:数组操作
http://blog.csdn.net/pipisorry/article/details/39496831
Array manipulation routines
numpy数组基本操作,包括copy, shape, 转换(类型转换), type, 重塑等等。这些操作应该都可以使用numpy.fun(array)或者array.fun()来调用。
Basic operations
copyto(dst, src[, casting, where])Copies values from one array to another, broadcasting as necessary.皮皮blog
Changing array shape
reshape(a, newshape[, order]) | Gives a new shape to an array without changing its data. |
ravel(a[, order]) | Return a contiguous flattened array. |
ndarray.flat | A 1-D iterator over the array.属性,会改变原数组。 |
ndarray.flatten([order]) | Return a copy of the array collapsed into one dimension.方法,不会改变原数组。 |
Array的形态操作-numpy更改数组的形状与数组堆叠
修改ndarray.shape属性 .shape · reshape() : 改变array的形态
可以通过修改shape属性,在保持数组元素个数不变的情况下,改变数组每个轴的长度。
下面的例子将数组c的shape改为(4,3),注意从(3,4)改为(4,3)并不是对数组进行转置,而只是改变每个轴的大小,数组元素在内存中的位置并没有改变:
>>> c.shape = 4,3 >>> c array([[ 1, 2, 3], [ 4, 4, 5], [ 6, 7, 7], [ 8, 9, 10]])
当某个轴的元素为-1时,将根据数组元素的个数自动计算此轴的长度,因此下面的程序将数组c的shape改为了(2,6):
>>> c.shape = 2,-1 >>> c array([[ 1, 2, 3, 4, 4, 5], [ 6, 7, 7, 8, 9, 10]])
使用数组的reshape方法,可以创建一个改变了尺寸的新数组,原数组的shape保持不变:
>>> d = a.reshape((2,2)) >>> d array([[1, 2], [3, 4]]) >>> a array([1, 2, 3, 4])
数组a和d其实共享数据存储内存区域,因此修改其中任意一个数组的元素都会同时修改另外一个数组的内容!
>>> a[1] = 100 # 将数组a的第一个元素改为100 >>> d # 注意数组d中的2也被改变了 array([[ 1, 100], [ 3, 4]])
Note: 需要注意的是,这里与MATLAB不一样,MATLAB变换是按列向量来的,而NUMPY是基于行向量
[[ 1. 4. ]
[ 2.2 5. ]
[ 3. 6. ]]
a.reshape(6,1) -- 将3x2矩阵变成列向量(6x1)
所以numpy的运行结果为:
[[ 1. ]
[ 4. ]
[ 2.2]
[ 5. ]
[ 3. ]
[ 6. ]] (列向量)
而MATLAB的运行结果为 : 1 2.2 3 4 5 6 (列向量)
注意: 对应的MATLAB很多向量默认为列向量,numpy中默认为行向量
numpy中多维数组转换为一维向量 · flatten(): 复制一个一维的array出来
ndarray.reshape(-1) {shape: (4,)} 或者 a.reshape(1, -1) {(1, 4)}
要注意的是reshape(返回?)后的数组不是原数组的复制,reshape前后的数组指向相同的地址(只是维度重新定义了一下)
也可以用flatten函数将高维数组转化为向量,和reshape不同的是,flatten函数会生成原始数组的复制
In [40]: a = np.array([[2,2], [2,3]])
In [41]: a.flatten()
Out[41]: array([2, 2, 2, 3])
In [43]: a.reshape(-1)
Out[43]: array([2, 2, 2, 3])
但是像这种不规则维度的多维数组就不能转换成功了,还是本身 a = np.array([[[2,3]], [2,3]])
.ravel() # flatten the array
· resize(): 也是改变array的形态。不同的是,resize是直接修改这个对象的,而reshape则会生成一个新的对象
皮皮blog
Transpose-like operations
rollaxis(a, axis[, start]) | Roll the specified axis backwards, until it lies in a given position. |
swapaxes(a, axis1, axis2) | Interchange two axes of an array. |
ndarray.T | Same as self.transpose(), except that self is returned if self.ndim < 2. |
transpose(a[, axes]) | Permute the dimensions of an array. |
· swapaxes(): 将n个维度中任意两个维度(坐标轴)进行调换
· transpose(): 这个就是矩阵的转置操作
Changing number of dimensions
atleast_1d(*arys) | Convert inputs to arrays with at least one dimension. |
atleast_2d(*arys) | View inputs as arrays with at least two dimensions. |
atleast_3d(*arys) | View inputs as arrays with at least three dimensions. |
broadcast | Produce an object that mimics broadcasting. |
broadcast_to(array, shape[, subok]) | Broadcast an array to a new shape. |
broadcast_arrays(*args, **kwargs) | Broadcast any number of arrays against each other. |
expand_dims(a, axis) | Expand the shape of an array. |
squeeze(a[, axis]) | Remove single-dimensional entries from the shape of an array. |
squeeze(a)
也就是将所有维度为1的维度去掉。这个操作应该等价于a.reshape(-1)。
scipy.spatial.distance.euclidean()函数源码:
u = np.asarray(u, dtype=dtype, order=‘c‘).squeeze() # Ensure values such as u=1 and u=[1] still return 1-D arrays.
使用示例1
In [54]: a = np.array([[2,2], [2,3]])
In [55]: a
array([[2, 2],
[2, 3]])
In [56]: a = a.reshape(1, -1)
In [57]: a
array([[2, 2, 2, 3]])
In [58]: a.shape
(1, 4)
In [59]: a.squeeze().shape
(4,)
使用示例2
In [19]: x = np.array([[[0], [1], [2]]])
In [20]: np.squeeze(x) #或者x.squeeze()
Out[20]: array([0, 1, 2])
In [21]: x.shape
Out[21]: (1, 3, 1)
In [22]: np.squeeze(x).shape
Out[22]: (3,)
Changing kind of array
asarray(a[, dtype, order]) | Convert the input to an array. |
asanyarray(a[, dtype, order]) | Convert the input to an ndarray, but pass ndarray subclasses through. |
asmatrix(data[, dtype]) | Interpret the input as a matrix. |
asfarray(a[, dtype]) | Return an array converted to a float type. |
asfortranarray(a[, dtype]) | Return an array laid out in Fortran order in memory. |
ascontiguousarray(a[, dtype]) | Return a contiguous array in memory (C order). |
asarray_chkfinite(a[, dtype, order]) | Convert the input to an array, checking for NaNs or Infs. |
asscalar(a) | Convert an array of size 1 to its scalar equivalent. |
require(a[, dtype, requirements]) | Return an ndarray of the provided type that satisfies requirements. |
皮皮blog
Joining arrays
concatenate((a1, a2, ...)[, axis]) | Join a sequence of arrays along an existing axis. |
stack(arrays[, axis]) | Join a sequence of arrays along a new axis. |
column_stack(tup) | Stack 1-D arrays as columns into a 2-D array. |
dstack(tup) | Stack arrays in sequence depth wise (along third axis). |
hstack(tup) | Stack arrays in sequence horizontally (column wise). |
vstack(tup) | Stack arrays in sequence vertically (row wise). |
numpy更改数组的形状与数组堆叠
numpy.concatenate()函数
函数原型:numpy.concatenate((a1, a2, ...), axis=0)
numpy.stack()函数
函数原型:numpy.stack(arrays, axis=0)
水平组合hstack和垂直组合vstack函数
对那些维度比二维更高的数组,hstack沿着第二个轴组合,vstack沿着第一个轴组合,concatenate允许可选参数给出组合时沿着的轴。
函数原型:numpy.hstack(tup)
其中tup是arrays序列,The arrays must have the same shape, except in the dimensioncorresponding toaxis (the first, by default).
等价于:np.concatenate(tup, axis=1)函数原型:numpy.vstack(tup)
等价于:np.concatenate(tup, axis=0) if tup contains arrays thatare at least 2-dimensional.
new_matrix=np.hstack([mat1,mat2])
或按行合并矩阵(要求两矩阵列数一样):
new_matrix=np.vstack([mat1,mat2])
合并矩阵的命令同样可以用于合并向量,但是合并向量的时候有时会提示行列数不对,那可能是因为一个的维度是(n个),而另一个的维度是(n列,1行),这种情况下,可用reshape来进行转换:
array2=array2.reshape(n)
new_array=np.hstack([array1,array2])
Note:函数column_stack以列将一维数组合成二维数组,它等同与vstack对一维数组。row_stack函数,另一方面,将一维数组以行组合成二维数组。
对那些维度比二维更高的数组,hstack沿着第二个轴组合,vstack沿着第一个轴组合,concatenate允许可选参数给出组合时沿着的轴。
在复杂情况下,r_[]和c_[]对创建沿着一个方向组合的数很有用,它们允许范围符号(“:”):
>>> r_[1:4,0,4]
array([1, 2, 3, 0, 4])
当使用数组作为参数时,r_和c_的默认行为和vstack和hstack很像,但是允许可选的参数给出组合所沿着的轴的代号。
Note: numpy.hstack()和numpy.column_stack()函数略有相似,numpy.vstack()与numpy.row_stack()函数也是挺像的。
[numpy vstack vs. column_stack]
深度组合numpy.dstack()
在数组的第三个轴(即深度)上组合,对应的元素都组合成一个新的列表,该列表作为新的数组的元素。This is a simple way to stack 2D arrays (images) into a single 3D array for processing.
函数原型:numpy.dstack(tup)
等价于:np.concatenate(tup, axis=2)
x, y = np.meshgrid(np.linspace(-1, 1, 3), np.linspace(-1, 1, 3)) print(‘x=\n‘, x) print(‘y=\n‘,y) print(‘stack = \n‘, np.dstack((x, y))) x= [[-1. 0. 1.] [-1. 0. 1.] [-1. 0. 1.]] y= [[-1. -1. -1.] [ 0. 0. 0.] [ 1. 1. 1.]] stack = [[[-1. -1.] [ 0. -1.] [ 1. -1.]] [[-1. 0.] [ 0. 0.] [ 1. 0.]] [[-1. 1.] [ 0. 1.] [ 1. 1.]]]可以看成是两个二维坐标值组合成三维坐标,可用于三维图形绘制。[三维绘图之matplotlib.mplot3d工具包]
行组合row_stack
行组合可将多个一维数组作为新数组的每一行进行组合
>>> one = arange(2)
>>> one
array([0, 1])
>>> two = one + 2
>>> two
array([2, 3])
>>> row_stack((one, two))
array([[0, 1],
[2, 3]])
对于2维数组,其作用就像垂直组合一样。
列组合column_stack
>>> column_stack((oned, twiceoned))
array([[0, 2],
[1, 3]])
对于2维数组,其作用就像水平组合一样。
不同stack函数使用示例
In [3]: a = np.array([1, 2, 3]) In [4]: b = np.array([2, 3, 4]) In [6]: print(a) [1 2 3] In [7]: print(b) [2 3 4] >>> np.stack((a, b)) array([[1, 2, 3], [2, 3, 4]])>>> np.vstack((a,b)) array([[1, 2, 3], [2, 3, 4]])>>> np.hstack((a,b)) array([1, 2, 3, 2, 3, 4])>>> np.dstack((a,b)) array([[[1, 2], [2, 3], [3, 4]]])
In [8]: a = np.array([[1], [2], [3]])
In [9]: b = np.array([[2], [3], [4]])
In [11]: print(a)
[[1]
[2]
[3]]
In [12]: print(b)
[[2]
[3]
[4]]>>> np.stack((a, b), axis=-1) array([[1, 2], [2, 3], [3, 4]])>>> np.vstack((a,b))
array([[1],
[2],
[3],
[2],
[3],
[4]])
In [14]: np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
In [15]: np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
#不处理xy的最后一列xy = np.hstack([preprocessing.scale(xy[:, 0:-1]), xy[:, -1].reshape(-1, 1)])
[NumPy简明教程(二、数组3)]
[Python numpy函数hstack() vstack() stack() dstack() vsplit() concatenate()]
皮皮blog
Splitting arrays
split(ary, indices_or_sections[, axis]) | Split an array into multiple sub-arrays. |
array_split(ary, indices_or_sections[, axis]) | Split an array into multiple sub-arrays. |
dsplit(ary, indices_or_sections) | Split array into multiple sub-arrays along the 3rd axis (depth). |
hsplit(ary, indices_or_sections) | Split an array into multiple sub-arrays horizontally (column-wise). |
vsplit(ary, indices_or_sections) | Split an array into multiple sub-arrays vertically (row-wise). |
Tiling arrays:numpy多维数组重塑
tile(A, reps) | Construct an array by repeating A the number of times given by reps. |
repeat(a, repeats[, axis]) | Repeat elements of an array. |
tile函数
模板numpy.lib.shape_base中的函数。
函数的形式是tile(A,reps)
假定A的维度为d,reps的长度为len
而长度为len的reps有len个数,进行tile函数运算时补足d位,前面加d-len个1,如下图所示:
经过tile运算,生成新的A,A的各维维度为:
Note:相乘的意思为,将原来A中每一维度的元素进行copy,生成的A中此元素出现次数为新的reps对应维度的数目。操作从低维度向高维进行。
举个栗子
Note:A的维度d=2 > len(reps)=1,这样reps补齐为(1,2),即A在0维上每个元素都copy为2倍,在1维上不copy.
W = np.tile([[3,5,6]],[3,1]) print(W)[[3 5 6]
[3 5 6]
[3 5 6]]
例三:
[Numpy的tile函数]
repeat
repeat(6,axis=0)表示的是将a按照第一轴的方向扩展6次得到的数组。axis=0表示的是按照第一轴的方向操作,也就是列方向上;若是axis=1就是行方向上面;这个也是等价于axis=-1的。因为-1表示的是它的最后那个轴方向。所以也就是行方向上面。
皮皮blog
Adding and removing elements
delete(arr, obj[, axis]) | Return a new array with sub-arrays along an axis deleted. |
insert(arr, obj, values[, axis]) | Insert values along the given axis before the given indices. |
append(arr, values[, axis]) | Append values to the end of an array. |
resize(a, new_shape) | Return a new array with the specified shape. |
trim_zeros(filt[, trim]) | Trim the leading and/or trailing zeros from a 1-D array or sequence. |
unique(ar[, return_index, return_inverse, ...]) | Find the unique elements of an array. |
append函数
(将一个列表加入多维数组ndarray中; 实现matlab data=http://www.mamicode.com/[data1;data2]的功能)
data1 = random.randint(1, 10, (2, 3)) data2 = random.randint(-10, -1, (2, 3)) data = append(data1, data2, axis=0) print(data1) print(data2) print() print(data) [[1 3 7] [8 3 3]] [[ -3 -8 -6] [ -3 -10 -10]] [[ 1 3 7] [ 8 3 3] [ -3 -8 -6] [ -3 -10 -10]]
Rearranging elements
fliplr(m) | Flip array in the left/right direction. |
flipud(m) | Flip array in the up/down direction. |
reshape(a, newshape[, order]) | Gives a new shape to an array without changing its data. |
roll(a, shift[, axis]) | Roll array elements along a given axis. |
rot90(m[, k]) | Rotate an array by 90 degrees in the counter-clockwise direction. |
ref: Array manipulation routines
numpy教程:数组操作