【问题标题】:Set none if numpy array index does not exist如果 numpy 数组索引不存在,则设置 none
【发布时间】:2013-02-04 02:15:26
【问题描述】:

我在 Python (2.7) 类中有一个函数,它应该在二维 numpy 数组中检索它周围的“单元格”的值。如果索引超出范围,我会将该值设置为无。

我正在努力寻找一种方法来做到这一点,而无需编写 8 个 try/catch 语句,或者不使用多个 if x else None 语句,如下面的代码所示。虽然它们都可以工作,但它们似乎结构不太好,我认为必须有一种更简单的方法来做到这一点 - 我可能会以完全错误的方式思考这个问题。任何帮助将不胜感激。

# This will return a dictionary with the values of the surrounding points
def get_next_values(self, column, row):
    if not (column < self.COLUMNS and row < self.ROWS):
        print "Invalid row/column."
        return False

    nextHorizIsIndex = True if column < self.COLUMNS - 2 else False
    nextVertIsIndex = True if row < self.ROWS - 2 else False

    n = self.board[column, row-1] if column > 0 else None
    ne = self.board[column+1, row-1] if nextHorizIsIndex else None
    e = self.board[column+1, row] if nextHorizIsIndex else None
    se = self.board[column+1, row+1] if nextHorizIsIndex and nextVertIsIndex else None
    s = self.board[column, row+1] if nextVertIsIndex else None
    sw = self.board[column-1, row+1] if nextVertIsIndex else None
    w = self.board[column-1, row] if row > 0 else None
    nw = self.board[column-1, row-1] if 0 not in [row, column] else None

    # debug
    print n, ne, e, se, s, sw, w, nw

【问题讨论】:

  • 注意负索引环绕...!
  • 我没想到,谢谢!

标签: python numpy python-2.7


【解决方案1】:

这是一个标准技巧:创建您的棋盘,并用值 None 填充边缘。然后您可以访问任何内部 3x3 正方形并使用

填充适当的值
nw, n, ne, w, _, e, sw, s, se = (self.board[column-1:column+2, row-1:row+2]).ravel()

例如,

import numpy as np

board = np.empty((10,10), dtype = 'object')
board[:,:] = None
board[1:9, 1:9] = np.arange(64).reshape(8,8)
print(board)
# [[None None None None None None None None None None]
#  [None 0 1 2 3 4 5 6 7 None]
#  [None 8 9 10 11 12 13 14 15 None]
#  [None 16 17 18 19 20 21 22 23 None]
#  [None 24 25 26 27 28 29 30 31 None]
#  [None 32 33 34 35 36 37 38 39 None]
#  [None 40 41 42 43 44 45 46 47 None]
#  [None 48 49 50 51 52 53 54 55 None]
#  [None 56 57 58 59 60 61 62 63 None]
#  [None None None None None None None None None None]]

column = 1
row = 1
nw, n, ne, w, _, e, sw, s, se = (board[column-1:column+2, row-1:row+2]).ravel()
print(nw, n, ne, w, _, e, sw, s, se)
# (None, None, None, None, 0, 1, None, 8, 9)

注意

  • 当您以这种方式定义板时,第一个非无索引现在是 1,而不是 0。
  • 我认为将第一个索引视为行更典型, 并将第二个索引作为列,因为当您 print(board) 这就是值的格式。所以也许你想要board[row-1:row+2, column-1:column+2]。当然,您可以定义自己的 print_board 函数,然后随意使用您喜欢的任何约定。

【讨论】:

  • 一个好技巧,但他们可能无法在具有数字 dtype 的数组中使用 None。可能必须使用 dtype object,这不是很“numpythonic”,或者使用 nan 而不是 None
  • 没错,如果 dtype 是浮点数,nan 可能是更好的选择。
  • 谢谢!这真的很有帮助——我也不知道board[:,:] = None 语法。我的 dtype 是 int,所以我试试用 nan 填充。
  • nanfloat dtypes 兼容,但与 int 不兼容。您需要为int 选择一个整数值。像-1 这样的负数可以吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2014-04-18
  • 2021-05-02
  • 2021-07-08
  • 1970-01-01
  • 2022-01-21
  • 2013-09-08
相关资源
最近更新 更多