Python Numpy Flat函数 [英] Python Numpy Flat Function
问题描述
numpy中的flat函数如何工作?另外,这些索引如何工作?请解释以下所有代码.
How does the flat function in numpy work? Also, how do these indexes work? Please explain all the following code.
res = zeros((n, n), v.dtype)
res[:n-k].flat[i::n+1] = v
推荐答案
flat
的简单用法:
In [410]: res = np.zeros((2,3), dtype=int)
In [411]: res
Out[411]:
array([[0, 0, 0],
[0, 0, 0]])
In [413]: res.flat[::2]=1
In [414]: res
Out[414]:
array([[1, 0, 1],
[0, 1, 0]])
In [415]: res.ravel()
Out[415]: array([1, 0, 1, 0, 1, 0])
flat
是flatten
和ravel
的变体.在这里,我将其分配给扁平化数组的每个其他元素1.您可以在ravel
表达式中看到这种情况.在同一数组的2d视图中,它不太明显.
flat
is a variant on flatten
and ravel
. Here I use it to assign 1 to every other element of the flattened array. You can see that happening in the ravel
expression. It's a bit less obvious in the 2d view of the same array.
在res[:n-k].flat[i::n+1] = v
中,第一个[:n-k]
选择res
的某些行.在我的示例中,flat[]
起作用,将v
中的值分配给展平数组中的任何n+1
元素.
In res[:n-k].flat[i::n+1] = v
, the first [:n-k]
selects some rows of res
. The flat[]
acts in my example, assigning values from v
to ever n+1
element in the flattened array.
再次通过一个小例子进行测试:
Again testing with a small example:
In [417]: res = np.zeros((5,5), dtype=int)
In [418]: res[:3]
Out[418]:
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
In [419]: res[:3].flat[2::6]
Out[419]: array([0, 0, 0])
In [420]: res[:3].flat[2::6]=[1,2,3]
In [421]: res
Out[421]:
array([[0, 0, 1, 0, 0],
[0, 0, 0, 2, 0],
[0, 0, 0, 0, 3],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
使用[i::n+1]
索引最终会在对角线上设置值.
The use of [i::n+1]
indexing ends up setting values on an diagonal.
或
In [422]: res = np.zeros((5,5), dtype=int)
In [424]: res.flat[0::6]
Out[424]: array([0, 0, 0, 0, 0])
In [425]: res.flat[0::6]=np.arange(5)
In [426]: res
Out[426]:
array([[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 2, 0, 0],
[0, 0, 0, 3, 0],
[0, 0, 0, 0, 4]])
这篇关于Python Numpy Flat函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!