从1d数组中的值开始切片2d数组 [英] Slicing 2d array from values in 1d array onwards

查看:101
本文介绍了从1d数组中的值开始切片2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有一个任意的二维数组(例如零)和一个索引数组:

Having an arbitrary 2d array, say of zeros, and an array of indices:

z = np.zeros((5,5))
ix = np.array([1,4,2,3,0])

如何从1d数组指定的列开始添加1,以获得:

How could I add a 1 from the columns specified by a 1d array onwards, in order to obtain:

array([[0, 1, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 1, 1, 1, 1]])

我无法使用numpy找到一种简单的方法.

I have not been able to find a simple way of doing so using numpy.

推荐答案

一种方法是-

In [50]: ncols = 5

In [51]: (ix[:,None] <= np.arange(ncols)).view('i1')
Out[51]: 
array([[0, 1, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 1, 1, 1, 1]], dtype=int8)

如果必须添加到现有数组z-

If you have to add to an existing array z -

z += (ix[:,None] <= np.arange(ncols))

这篇关于从1d数组中的值开始切片2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆