查找数组中每个元素与另一个数组的相对比例

时间:2019-08-24 17:54:02

标签: python-3.x numpy

我有两个数组:A和B。

A = np.array([65, 20, 140, 15, 75, 15])
B = np.array([15, 45, 75, 106, 135, 165])

A可以看作是形状为(n,1)的用户输入,其中n是任意正整数。 B可以认为是形状为(m,1)的固定规格,其中m是固定的且已知。

我正在尝试获取数组A的每个元素相对于数组B的相对比例。结果将是形状为(n,m)的矩阵M,如下所示:

M

array([[0.  , 0.33, 0.67, 0.  , 0.  , 0.  ],
       [0.83, 0.17, 0.  , 0.  , 0.  , 0.  ],
       [0.  , 0.  , 0.  , 0.  , 0.83, 0.17],
       [1.  , 0.  , 0.  , 0.  , 0.  , 0.  ],
       [0.  , 0.  , 1.  , 0.  , 0.  , 0.  ],
       [0.67, 0.33, 0.  , 0.  , 0.  , 0.  ]])

在M的第一行中,第二个和第三个元素分别为0.33和0.67,因为65(A的第一个元素)占B的45和75(第二个和第三个)元素的33%/ 67%。

M[0,1] = (75 - 65) / (75-45)
M[0,2] = 1 - M[0,1]

我一直在环顾四周,但是似乎没有核心功能可以做到这一点。

非常感谢,

2 个答案:

答案 0 :(得分:0)

我相信可以对其进行优化,但是似乎可以正常工作:

def f(ar: np.ndarray, br: np.ndarray):
    m = np.zeros((ar.shape[0], br.shape[0]))
    for ar_el, m_row in zip(ar, m):
        left = br[br <= ar_el]
        right = br[br >= ar_el]
        left_e = left[-1]
        right_e = right[0]
        if left_e == right_e:
            m_row[len(left) - 1] = 1
        elif left_e == br[-1]:
            m_row[-1] = 1
        elif right_e == br[0]:
            m_row[0] = 1
        else:
            m_row[len(left) - 1] = (right_e - ar_el) / (right_e - left_e)
            m_row[len(left)] = (ar_el - left_e) / (right_e - left_e)
    return m

数据的结果:

>>> np.around(f(a, b), decimals=2)
array([[0.  , 0.33, 0.67, 0.  , 0.  , 0.  ],
   [0.83, 0.17, 0.  , 0.  , 0.  , 0.  ],
   [0.  , 0.  , 0.  , 0.  , 0.83, 0.17],
   [1.  , 0.  , 0.  , 0.  , 0.  , 0.  ],
   [0.  , 0.  , 1.  , 0.  , 0.  , 0.  ],
   [1.  , 0.  , 0.  , 0.  , 0.  , 0.  ]])

答案 1 :(得分:0)

假设B已排序,并且min(B)<=min(A)max(A)<max(B)

idx = B.searchsorted(A,'right')
d = np.diff((B[idx],A,B[idx-1]),axis=0)
out = np.zeros((A.size,B.size))
np.put_along_axis(out,np.add.outer(idx,(-1,0)),(d/d.sum(axis=0)).T,axis=1)

np.round(out,3)
# array([[0.   , 0.333, 0.667, 0.   , 0.   , 0.   ],
#        [0.833, 0.167, 0.   , 0.   , 0.   , 0.   ],
#        [0.   , 0.   , 0.   , 0.   , 0.833, 0.167],
#        [1.   , 0.   , 0.   , 0.   , 0.   , 0.   ],
#        [0.   , 0.   , 1.   , 0.   , 0.   , 0.   ],
#        [1.   , 0.   , 0.   , 0.   , 0.   , 0.   ]])