Skip to content

Commit

Permalink
add np.roll
Browse files Browse the repository at this point in the history
  • Loading branch information
llinjupt committed Apr 22, 2019
1 parent 77eb9d6 commit 5775684
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions numpy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4618,6 +4618,93 @@ np.transpose 默认对所有轴按中心对称方式交换。我们也可以通
---------------------------------------------------
| 000 | 001 | 002 | 010 | 011 | 012 | A.transpose元素的索引
按轴滚动
~~~~~~~~~~~
np.roll(a, shift, axis=None) 将数组 a 沿着 axis 的方向,滚动 shift 长度可以向后滚动特定的轴到一个指定位置。如果不指定 axis 则默认先进行展平操作,然后按照向量滚动,最后按原 shape 返回。
.. code-block:: python
:linenos:
:lineno-start: 0
# a 为向量
a = np.arange(10)
print(a)
>>>
[0 1 2 3 4 5 6 7 8 9]
# shift 为正数表示向右滚动
b = np.roll(a, 2)
print(b)
>>>
[8 9 0 1 2 3 4 5 6 7]
# shift 为负数表示向左滚动
c = np.roll(a, -2)
print(c)
>>>
[2 3 4 5 6 7 8 9 0 1]
a 为向量,只有一个轴,滚动操作默认 axis = 0,可以不指定。shift 正负决定了滚动方向。多维矩阵:
.. code-block:: python
:linenos:
:lineno-start: 0
a = np.reshape(np.arange(12), (4,3))
print(a)
>>>
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
# 沿着 0 轴(垂直方向滚动 1 行)
print(np.roll(a, 1, axis=0))
>>>
[[ 9 10 11]
[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
# 沿着 1 轴(水平方向滚动 1 行)
print(np.roll(a, 1, axis=1))
>>>
[[ 2 0 1]
[ 5 3 4]
[ 8 6 7]
[11 9 10]]
# 展平后滚动再按原 shape 返回
print(np.roll(a, 1))
>>>
[[11 0 1]
[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
对于二维或者多维矩阵,shift 和 axis 可以指定滚动某一维,也可以通过 tuple 指定多维。
.. code-block:: python
:linenos:
:lineno-start: 0
# 相当于多次滚动操作,先在 0 轴滚动 1 次,然后再在 1 轴滚动 1次
print(np.roll(a, (1,1), axis=(0,1)))
>>>
[[11 9 10]
[ 2 0 1]
[ 5 3 4]
[ 8 6 7]]
滚动轴
~~~~~~~~~~~
Expand Down

0 comments on commit 5775684

Please sign in to comment.