Python Numpy:合并并返回第一个非零观察

时间:2016-10-23 21:18:26

标签: python arrays numpy coalesce

我目前是NumPy的新手,但对SQL非常熟练。 我在SQL中使用了一个名为coalesce的函数,我很失望在NumPy中找不到。我需要此函数从2个数组创建第三个数组want,即array1array2,其中array1中的零/缺失观测值被array2中的观测值替换在相同的地址/位置下。我无法弄清楚如何使用np.where

完成此任务后,我想采用此数组want的较低对角线,然后填充最终数组want2,注意 第一个非零 观察。如果所有观察结果,即coalesce(array1, array2)want2中返回丢失或0,则默认为零。

我写了一个展示所需行为的例子。

import numpy as np
array1= np.array(([-10,0,20],[-1,0,0],[0,34,-50]))
array2= np.array(([10,10,50],[10,0,25],[50,45,0]))

# Coalesce array1,array2 i.e. get the first non-zero value from array1, then from array2. 
# if array1 is empty or zero, then populate table want with values from array2 under same address
want=np.tril(np.array(([-10,10,20],[-1,0,25],[50,34,-50])))

print(array1)
print(array2)
print(want)

# print first instance of nonzero observation from each column of table want
want2=np.array([-10,34,-50])
print(want2)

1 个答案:

答案 0 :(得分:2)

" Coalesce":使用putmask将{0}的值替换为array2的值:

want = array1.copy()
np.putmask(array1.copy(), array1==0, array2)

np.tril(want)每列的第一个非零元素:

where_nonzero = np.where(np.tril(want) != 0)

"""For the where array, get the indices of only 
the first index for each column"""
first_indices = np.unique(where_nonzero[1], return_index=True)[1]

# Get the values from want for those indices
want2 = want[(where_nonzero[0][first_indices], where_nonzero[1][first_indices])]