bool 值作为索引的 Python 效果 (a[a==0] = 1)

标签 python arrays numpy indexing boolean-indexing

我目前正在实现一些我在 github 上看到的代码。

( https://gist.github.com/karpathy/a4166c7fe253700972fcbc77e4ea32c5 )

这里的兴趣点如下:

def prepro(I):
   """ prepro 210x160x3 uint8 frame into 6400 (80x80) 1D 
   float vector """
   I = I[35:195] # crop
   I = I[::2,::2,0] # downsample by factor of 2
   I[I == 144] = 0 # erase background (background type 1)
   I[I == 109] = 0 # erase background (background type 2)
   I[I != 0] = 1 # everything else (paddles, ball) just set to 1
   return I.astype(np.float).ravel()

作者在这里对图像进行预处理,以训练神经网络。我感到困惑的部分是:

I[I == 144] = 0 # erase background (background type 1)
I[I == 109] = 0 # erase background (background type 2)
I[I != 0] = 1 # everything else (paddles, ball) just set

我认为作者想将列表中所有值为 144(109,而不是 0)的元素设置为特定值。但如果我是正确的, bool 值在 python 中只代表 0 或 1。因此,将列表与整数进行比较总是会得到 False,因此结果为 0。

这使得 I[I==x] <=> I[0] : x is integer那么为什么还要费心去做呢?

我在这里错过了什么?

最佳答案

NumPy 数组有点不同;它们的使用类似于 MATLAB 中的使用。

I == 144 生成一个逻辑数组,其维度与 I 相同,其中 144 的所有位置在 I true,所有其他为 false

(其他表达式也一样)

使用这样的逻辑数组进行索引意味着索引为true的所有位置都会受到赋值的影响。

关于 bool 值作为索引的 Python 效果 (a[a==0] = 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59303270/

相关文章:

python - 绘制 csv 的 2 列并出现 matplotlib 错误

python - Celery worker 在 virtualenv 中从命令行工作,但不作为守护进程工作

python - 如果大于 len,Pandas 会更改列值

php - 在单独的行中插入数组值

python - 在python中对不均匀采样数据进行拉普拉斯算子

python - 找出数据集中哪些特征共线

python - 将 8 位值转换为 24 位值

java - 如何确定我的数组是否为空

python - 根据条件计算 Dataframe 中的正负连续元素

python - import arcpy 导致 ImportError : cannot import name shares_memory