pythonflat怎么设置,Python 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

解决方案

A simple use of 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 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.

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]])

The use of [i::n+1] indexing ends up setting values on an diagonal.

or

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]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值