In [1]: import numpy as np
In [2]: a = np.arange(9)
In [3]: a[3:7]
Out[3]: array([3, 4, 5, 6])
In [4]: a[:7:2]
Out[4]: array([0, 2, 4, 6])
In [5]: a[::-1]
Out[5]: array([8, 7, 6, 5, 4, 3, 2, 1, 0])
Slicing of one-dimensional NumPy arrays works just like the slicing of standard Python lists.
We can manipulate arrary shapes using the following functions:
Ravel:We can accomplish this with the ravel() function as follows:
In [22]: import numpy as np
In [23]: b = np.arange(24).reshape(2,3,4)
In [24]: b
Out[24]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Flatten:The appropriately named function,flatten(),dose the same as travel().However,flatten() always allocates new memory,where as ravel might give back a view of the array.This means that we can directly manipulate the array as follows:
In [25]: b.flatten()
Out[25]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
Setting the shape with a tuple:Besides the reshape() function,we can also define the shape straightaway with a tuple,which is exhibited as follows:
In [26]: b.shape = (6,4)
In [27]: b
Out[27]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
As you can understand,the preceding code alters the array immediately.Now,we have a 6*4 array.
Transpose:In linear algebra,it is common to transpose matrices.Transposing is a way to transform data.For a two-dimensional table,transposing means that rows become columns and cloumns become rows.We can do this too by using the following code:
In [33]: a = b.transpose()
In [34]: a
Out[34]:
array([[ 0, 4, 8, 12, 16, 20],
[ 1, 5, 9, 13, 17, 21],
[ 2, 6, 10, 14, 18, 22],
[ 3, 7, 11, 15, 19, 23]])
Resize:The resize() method works just like the reshape() method,but changes the array it works on:
In [37]: b.resize((2,12))
In [38]: b
Out[38]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
numpy 学习2
最新推荐文章于 2024-07-24 23:27:06 发布