考虑一个numpy2D整数数组,其中一些条目是0(array1)。考虑一个不同的二维数组(array2),其中第一列具有与array1相同的非零值,而另一列(比如索引2)具有不同的数值(float)。你知道吗
如何通过将array1中的每个非零条目替换为array2的第2列的相应值来创建新的array3?你怎么做到超级干净?你知道吗
示例:
>>> array1
array([[0, 27, 43, 10],
[0, 80, 15, 2],
[0, 3, 6, 9]])
>>> array2
array([[ 10., 4., 88.],
[ 2., 2., 95.],
[ 9., 2., 65.],
[ 43., 1., 62.],
[ 15., 5., 64.],
[ 6., 6., 67.],
[ 27., 5., 62.],
[ 80., 8., 73.],
[ 3., 9., 59.]])
>>> array3
array([[0., 62., 62., 88.],
[0., 73., 64., 95.],
[0., 59., 67., 65.]])
可以将布尔索引与高级numpy数组索引一起使用:
结果是:
解释
首先创建一个布尔数组,该数组指示存在非零项的位置:
这将用于查找应替换的元素。你知道吗
然后需要找到这些元素的值:
因为您的
array2
是有序的,并且从值1开始,所以我们需要减去1来找到替换值的适当行。如果您的array2
没有排序,您可能需要对其进行排序或在两者之间执行另一个索引:然后将这些值赋给原始数组或新数组:
这种方法依赖于
array2
的排序,因此如果有更复杂的条件,它将中断。但这要么需要找到值和索引之间的关系并插入它,而不是我做的简单的-1
,要么需要做另一个中间的np.where
/布尔索引。你知道吗扩展
如果没有已排序的
array2
而无法对其排序,则可以执行以下操作:因为这样可以互相广播数组,所以您将创建一个大小为
array1.size * array1.size
的数组。所以这可能不是很有效,但仍然完全矢量化。你知道吗麻木(如果你想要速度)
numba是伟大的,如果你想加快事情会很慢,因为没有原生的numpy或scipy版本。如果您有anaconda或conda,那么它已经安装,因此可能是一个可行的选择:
特别是对于大型阵列,这显然是最快和内存效率最高的解决方案,因为没有创建临时阵列。第一次调用会慢很多,因为函数需要动态编译。你知道吗
时间安排:
你知道吗 我不确定我是否理解您的要求,但让我们试试list comprehensions:
但很难阅读,我更喜欢列表:
相关问题 更多 >
编程相关推荐