Python Numpy : Coalesce and return first nonzero observation

标签 python arrays numpy coalesce

我目前是 NumPy 的新手,但非常精通 SQL。 我在 SQL 中使用了一个名为 coalesce 的函数,很遗憾在 NumPy 中没有找到该函数。我需要这个函数从 2 个数组(即 array1array2)创建第三个数组 want,其中 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)

最佳答案

“合并”:使用 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])]

关于Python Numpy : Coalesce and return first nonzero observation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207906/

相关文章:

Numpy FFT 稳定性

python - 第一次出现大于 numpy 数组中给定值的值

python - 如何在 Odoo 日期时间字段中显示不同的日期格式?

python - 无法摆脱不需要的输出

python - 如何使用 docker 容器中的 Singularity 运行 python 程序?

arrays - 数据在 UItableview 的部分重复

arrays - 为什么线性探测使用相对主要的步骤?

python - 将字典保存到文件(numpy 和 Python 2/3 友好)

python - python Selenium 包中的格式错误

c++ - 具有构造函数的对象数组