在Numpy数组的列内进行条件替换 [英] Conditional Replace within a Column of a Numpy Array

查看:176
本文介绍了在Numpy数组的列内进行条件替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组,例如:

I have a numpy array, for example:

theData= [[0, 1, 1, 1],[0, 1, 3, 1],[3, 4, 1, 3],[0, 1, 2, 0],[2, 1, 0, 0]]

如何用-1替换第一列中的所有零

很容易用 theData [theData == 0] = -1 替换整个数组中的所有零,所以我认为这样可以工作

It's easy to replace all the zeros in the whole array with theData[theData==0] = -1, so I thought something like this would work

theData[theData[:,0] == 0] = -1
theData[:,0 == 0] = -1

但这会将行中所有行的所有值更改为-1第一列值为零。不是我的目标,我想将替换限制在第一列(或任何其他列)。

but these change all values across the row to -1 for any row in which the first column value is zero. Not my goal, I want to limit the replacement to the first (or whatever) column.

显然,这可以通过循环来完成。也可以通过将第一列提取为一维数组,在其中进行替换,然后将其转置复制到原始第一列上来完成。但是我怀疑有一种更快,更Pythonic的方法可以做到这一点。也许使用np.where,但我无法弄清楚。

This can obviously be done with a loop. It can also be done by extracting the first column as 1D array, doing the replacement within it, then copying its transpose over the original first column. But I suspect there is a faster and more Pythonic way to do this. Perhaps using np.where, but I can't figure it out.

推荐答案

您可以直接为该列建立索引不要用它建立一个不同的对象。检查以下示例:

You can index that column directly as long as you don't build a different object with it. Check the following example:

theData= np.array([[0, 1, 1, 1],[0, 1, 3, 1],[3, 4, 1, 3],[0, 1, 2, 0],[2, 1, 0, 0]])
print(theData)
theData[:,0][theData[:,0] == 0] = -1
print(theData)

结果是这样的:

[[0 1 1 1]
 [0 1 3 1]
 [3 4 1 3]
 [0 1 2 0]
 [2 1 0 0]]
[[-1  1  1  1]
 [-1  1  3  1]
 [ 3  4  1  3]
 [-1  1  2  0]
 [ 2  1  0  0]]

这篇关于在Numpy数组的列内进行条件替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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