Skip to content

Commit

Permalink
update np.repeat
Browse files Browse the repository at this point in the history
  • Loading branch information
llinjupt committed May 7, 2019
1 parent c9d5cdd commit b57eb1a
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions numpy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1279,7 +1279,7 @@ ndarray 对象 copy() 方法可以方便对数组对象的复制:
repeat
~~~~~~~~~~~~~

np.repeat 对元素或者数组进行重复以填充新数组,在深入介绍它之前,先看一个例子:
np.repeat 对数组进行 **逐元素** 重复以生成新数组,在深入介绍它之前,先看一个例子:

.. code-block:: python
:linenos:
Expand All @@ -1298,15 +1298,15 @@ np.repeat 生成了向量,把 3 重复了 4 次。np.repeat 可以完成更复
Repeat elements of an array.

- a 可以是一个数,也可以是数组。
- axis=None,时会进行 a.flatten(),实际上就是变成了一个行向量,否则指定重复特定的轴
- axis=None,时会进行 a.flatten(),实际上就是变成一向量,否则在指定的轴上重复
- repeats 可以为一个数,也可以为一个序列或数组,它会被广播以匹配要复制的轴的形状。

我们分析上面示例的实现过程:

1. 如果 a 不是数组,首先把 a 转换为 1维数组,这里 a 为 3,转换为 [3]
1. 如果 a 不是数组,首先把 a 转换为 1 维数组,这里 a 为 3,转换为 [3]
2. 由于 aixs = None,所以对 a 展平成一维数组,a.flatten() 也即 [3]
3. a.shape 为 (1,),repeats 转换为 [4],shape 为 (1,),形状相同,如果不同按照广播规则扩展为相同
4. 最后元素 3 对应的重复为 4,也即 3 重复 4 次:[3 3 3 3]
4. 最后元素 3 对应的重复次数为 4,也即 3 重复 4 次得到 [3 3 3 3]

再看一个稍微复杂的例子,可以看出最终重复是以单个元素为单位的:

Expand All @@ -1326,9 +1326,9 @@ np.repeat 生成了向量,把 3 重复了 4 次。np.repeat 可以完成更复
>>>
[1 1 2 2 3 3 4 4]
展平后的 shape 为 (4,),而 repeat.shape 为 (1,),所以广播扩展为 [2 2 2 2],然后各元素按照重复次数进行重复
展平后的 shape 为 (4,),而 repeat.shape 为 (1,),所以广播扩展为 [2 2 2 2],然后各元素按照对应的重复次数进行重复

下面的示例展示 axis = n 的作用:
下面的示例展示 axis = n 的作用,注意 axis 参数不可以超过指定的数组维数

.. code-block:: python
:linenos:
Expand Down

0 comments on commit b57eb1a

Please sign in to comment.