【问题标题】:Python Numpy: Coalesce and return first nonzero observationPython Numpy:合并并返回第一个非零观测值
【发布时间】:2017-03-05 14:38:48
【问题描述】:

我目前是 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)

【问题讨论】:

    标签: python arrays numpy coalesce


    【解决方案1】:

    “合并”:使用putmask 将等于零的值替换为来自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])]
    

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多