如何修改除特定列索引之外的每一行中的Numpy 2D数组? [英] How to modify a Numpy 2D array in every row but specific column indexes?

查看:62
本文介绍了如何修改除特定列索引之外的每一行中的Numpy 2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我现在要实现的目标。

This is what I am doing now to achieve what I want.

In: 
a=numpy.zeros((3,2))
a[range(a.shape[0]),[0,0,1]] = 1
a
Out:
array([[ 1.,  0.],
       [ 1.,  0.],
       [ 0.,  1.]])

如您所见,我使用 range 函数选择a中的所有行。还有其他更清洁的方法来选择每一行吗?

As you can see, I used range function to select all the rows in a. Is there any other cleaner way to select every row?

推荐答案

正在做 这件事 可以更干净地完成,因为您只是在构建单热点阵列,并且 答案,用于干净的方式来实现 numpy 。我推荐 @MartinThoma撰写的:

Doing this specific thing can be done more cleanly, as you're just constructing a one-hot array, and there are good answers for "clean" ways to do this in numpy. I recommend this one by @MartinThoma:

a = np.eye(2)[[0,0,1]]

此外,大多数机器学习软件包都有自己的一站式编码方法,该方法将比这种方法更为有效和干净,因为机器学习是一站式编码的最常见用法。

Also, most machine learning packages have their own one-hot encoding method that will be even more efficient and "clean" than this one, as machine learning is the most common use of one-hot encoding.

但是,通常无法在执行这种精美索引时消除范围坐标。确实没有一种清晰明了的方式来表示该操作,当您要将表示法扩展到2维以上时,这不会造成混淆。 numpy

However, in general eliminating the range coordinate when doing this sort of fancy indexing is not possible. There really isn't a clear, explicit way to represent that operation that wouldn't be confusing when you want to extend the representation beyond 2 dimensions. And working in more than 2 dimensions at a time is the whole point of numpy

这篇关于如何修改除特定列索引之外的每一行中的Numpy 2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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