np.where return 一个包含 numpy 数组的空数组
np.where return an empty array with numpy array in it
我有这个:
import numpy as np
mol= np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20], [21], [22], [23], [24], [25], [26], [27]])
i = np.where(mol == 7)
print(i)
但是 return
(array([], dtype=int64),)
此外,如果我这样做
i = np.where(mol == 7)
return一样
有什么问题吗?谢谢!
当您创建带有锯齿状列表的 numpy 数组时,生成的 numpy 数组将是 dtype object
并包含列表。
>>> x = np.array([[1], [1,2]])
>>> x
array([list([1]), list([1, 2])], dtype=object)
您可以清楚地看到与您的输入列表相同的结果:
array([list([0, 1, 2, 3, 4]), list([5, 6, 7, 8, 9]),
list([10, 11, 12, 13, 14]), list([15, 16, 17, 18, 19]), list([20]),
list([21]), list([22]), list([23]), list([24]), list([25]),
list([26]), list([27])], dtype=object)
这就是为什么 np.where
找不到您的值,您无法使用 np.where
[=35 搜索列表=].将此与不包含 lists
:
的非锯齿状数组进行比较
x = np.arange(28).reshape(7, -1)
In [21]: np.where(x==7)
Out[21]: (array([1]), array([3]))
如果你想解决这个问题,你可以不使用锯齿状数组,这通常很麻烦,或者你可以用[=19之类的东西填充你的数组=]:
top = max([len(i) for i in mol])
mol = np.asarray([np.pad(i, (0, top-len(i)), 'constant', constant_values=-1) for i in mol])
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, -1, -1, -1, -1],
[21, -1, -1, -1, -1],
[22, -1, -1, -1, -1],
[23, -1, -1, -1, -1],
[24, -1, -1, -1, -1],
[25, -1, -1, -1, -1],
[26, -1, -1, -1, -1],
[27, -1, -1, -1, -1]])
这将使您能够再次使用 np.where
In [40]: np.where(mol==7)
Out[40]: (array([1]), array([2]))
我有这个:
import numpy as np
mol= np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20], [21], [22], [23], [24], [25], [26], [27]])
i = np.where(mol == 7)
print(i)
但是 return
(array([], dtype=int64),)
此外,如果我这样做
i = np.where(mol == 7)
return一样
有什么问题吗?谢谢!
当您创建带有锯齿状列表的 numpy 数组时,生成的 numpy 数组将是 dtype object
并包含列表。
>>> x = np.array([[1], [1,2]])
>>> x
array([list([1]), list([1, 2])], dtype=object)
您可以清楚地看到与您的输入列表相同的结果:
array([list([0, 1, 2, 3, 4]), list([5, 6, 7, 8, 9]),
list([10, 11, 12, 13, 14]), list([15, 16, 17, 18, 19]), list([20]),
list([21]), list([22]), list([23]), list([24]), list([25]),
list([26]), list([27])], dtype=object)
这就是为什么 np.where
找不到您的值,您无法使用 np.where
[=35 搜索列表=].将此与不包含 lists
:
x = np.arange(28).reshape(7, -1)
In [21]: np.where(x==7)
Out[21]: (array([1]), array([3]))
如果你想解决这个问题,你可以不使用锯齿状数组,这通常很麻烦,或者你可以用[=19之类的东西填充你的数组=]:
top = max([len(i) for i in mol])
mol = np.asarray([np.pad(i, (0, top-len(i)), 'constant', constant_values=-1) for i in mol])
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, -1, -1, -1, -1],
[21, -1, -1, -1, -1],
[22, -1, -1, -1, -1],
[23, -1, -1, -1, -1],
[24, -1, -1, -1, -1],
[25, -1, -1, -1, -1],
[26, -1, -1, -1, -1],
[27, -1, -1, -1, -1]])
这将使您能够再次使用 np.where
In [40]: np.where(mol==7)
Out[40]: (array([1]), array([2]))