【问题标题】:Direct indexing into 2d Numpy array using another Numpy array as the (y,x) coordinates使用另一个 Numpy 数组作为 (y,x) 坐标直接索引到 2d Numpy 数组
【发布时间】:2019-12-06 01:01:32
【问题描述】:

我四处寻找这是否可能......这似乎很简单,所以也许我错过了一些东西。

我有一个 2D numpy 数组:

#####################################
################################FFFF#
################################....#
################################....#
################################....#
################################....#
#S..................................#
#S..................................#
#S..................................#
#S..................................#
#####################################

我想将其中一个“S”替换为“@”符号。我写了一个函数来查找一个'S'的索引:

def findStart(env):
    y = np.nonzero(env == 'S')[0]
    x = np.nonzero(env == 'S')[1]

    y = [round(len(y)/2)]
    x = [round(len(y)/2)]
    return y,x

yStart,xStart = findStart(env)

产生:

print('Starting point [y,x]: ', yStart,',',xStart)
Starting point [yStart,xStart]:  8 , 1

然后我创建一个 numpy 数组:

startCoord = np.array([yStart,xStart])

我想简单地使用 startCoord 访问 env[yStart, xStart],如下所示:

env[startCoord] = '@'

应该返回以下内容:

#####################################
################################FFFF#
################################....#
################################....#
################################....#
################################....#
#S..................................#
#S..................................#
#@..................................#
#S..................................#
#####################################

我尝试过使用 np.put 和 np.flatten,但 '@' 被放置在错误的位置。最简单的方法是什么?

【问题讨论】:

  • 您确定以这种方式替换哪个 S 是否有原因?
  • @DerekEden 并不特别。我想将坐标保持为一个对象,因此使用了 startCoord。下线,我需要使用更多坐标,所以我真的很想知道如何使用 startCoord 访问数组。至于我如何替换它,原因是我是一个 python nooby 并且不知道更好的选择! :)

标签: python arrays numpy


【解决方案1】:

根据您的评论...这可能是一种可以帮助您的方法:

假设你的数组被称为arr

import random
ids = np.where(np.equal(arr,'S'))
ids = [(row,col) for row,col in zip(ids[0],ids[1])] #might be a better way to do this
rand_id = random.sample(ids,1)[0]
arr[rand_id] = '@'

这里,rand_id 是一个随机选择的行,arr 中的列位置,其中包含要更改的所需值...ids 包含具有此值的所有行、列位置

定义ID的第二步只是将它们放入行列表中,col tuples

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 2011-07-27
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多