使用IF条件切片多维NumPy数组

时间:2018-10-20 18:18:41

标签: arrays python-3.x numpy slice

我是python的新手,我正在尝试编写一个函数来切片多维numpy数组。有几个要求:

  1. 如果i和j都不是None值,则返回数组a的元素
  2. 如果我不是None值但j为None,则返回数组a的第i行。
  3. 如果j不是None值但i为None,则返回数组a的列j。

-

def function(a,j,i):
    if i is not None and j is not None:
        return a
    elif i is not None and j is None:
        return a[i-1]
    elif i is None and j is not None:
        return a[:,j-1]

我现在正在执行此操作,但是出现一个错误,提示ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all()。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

它对我有用,但您可能可以这样做:

def function(a,j,i):
    return a[i, j] # None is treated as : in np, so no need to filter for it.

这会得到您想要的。.

此外,您的逻辑中还有一个错误:

if i is not None and j is not None:
    return a

你是说

if i is None and j is None:
    return a