我有一个3d数组,我想找到每个元素的坐标值1。我使用numpy,这是我的数组:
table = np.array([
[
[1,4,8,6],
[8]],
[
[4],
[9],
[5]],
[
[6],
[4]],
[
[2],
[1]]])基于与this相关的问题,我有以下代码:
print(np.argwhere(table == 1))这段代码为一个“简单”的3d数组做了我想做的事情(打印3D-值出现的坐标)。但对我的阵列不起作用。
为什么我的当前代码不能在我的数组上工作?如何在我的数组上获得相同的结果?
它正在处理的数组:
table = np.array([
[
[ 1, 2, 3],
[ 8, 4, 11]],
[
[ 1, 4, 4],
[ 8, 5, 9]],
[
[ 3, 8, 6],
[ 11, 9, 8]],
[
[ 3, 7, 6],
[ 9, 3, 7]]])发布于 2020-07-14 15:29:03
当您打印(第一个)表时,结果是:
array([list([[1, 4, 8, 6], [8]]), list([[4], [9], [5]]), list([[6], [4]]),
list([[2], [1]])], dtype=object)也就是说,它是一个一维数组,包含4个列表类型的元素.
np.where找不到1的实例的原因是它查看每个元素并将其与给定的值进行比较。这个函数在检查数组的特定元素时,是否没有“潜入”这个对象(不检查元素的各个子元素(如果是列表))。
np.where在检查一个元素(列表类型)时所做的所有检查工作:这个元素是== 1。因为它不是,所以它被视为非匹配元素。其他元素也是。
从15.07开始在注释后面编辑
如果将表定义为:
table2 = np.array(list([
list([[1,4,8,6], [8,0,0,0], [0,0,0,0]]),
list([[4,0,0,0], [9,0,0,0], [5,0,0,0]]),
list([[6,0,0,0], [4,0,0,0], [0,0,0,0]]),
list([[2,0,0,0], [1,0,0,0], [0,0,0,0]])]))(在所有的大小相同的列表中),Pandas足够聪明地将其转换为:
array([[[1, 4, 8, 6],
[8, 0, 0, 0],
[0, 0, 0, 0]],
[[4, 0, 0, 0],
[9, 0, 0, 0],
[5, 0, 0, 0]],
[[6, 0, 0, 0],
[4, 0, 0, 0],
[0, 0, 0, 0]],
[[2, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 0]]])运行table.shape,您将看到(4, 3, 4)。
然后运行table.dtype,您将看到dtype('int32'),因此它现在是_int_s的“常规”Numpy数组。
在这种情况下,np.argwhere(table == 1)会找到只包含1的单元格索引。
但你的桌子是如此“奇怪”的情况,潘达不是为之设计的。
要在这些(嵌套的)列表中定位每个1的索引,您可以遍历数组(使用nd.iter),并在每个元素中查找索引(如果有的话)。类似于:
it = np.nditer(table, flags=['f_index', 'refs_ok'])
for x in it:
print(f'Index {it.index}: {x}')
res = [(i, el.index(1)) for i, el in enumerate(x[()]) if 1 in el]
if len(res) == 0:
print(' Nothing found')
else:
print(f' Found at: {res}')注意,在x之后有一些奇怪的构造,即()。原因是:
objects.
[()]是获取唯一包含的对象的方法)。通过索引访问元素,但是索引值是空元组(没有实际索引值)。对于您的表,上面的代码打印:
Index 0: [[1, 4, 8, 6], [8]]
Found at: [(0, 0)]
Index 1: [[4], [9], [5]]
Nothing found
Index 2: [[6], [4]]
Nothing found
Index 3: [[2], [1]]
Found at: [(1, 0)]如果需要的话,重新加工以适应你的需要。
https://stackoverflow.com/questions/62897738
复制相似问题