如何以最佳方式加入两个 ndarrys 中的两个 X-Y 图

how to join two X-Y plots held in two ndarrys optimally

我想合并两个在 X 轴上可能不同的 XY 图。 这些图保存在 numpy ndarrys 中,我希望连接操作是最佳的,性能明智的(我知道如何用关联数组解决这个问题)。

联合操作定义为PlotAB = join_op(PlotA,PlotB):

PlotA = 
array([[2, 5],
       [3, 5],
       [5, 5])

其中 plotA[:,0] 是 X 轴,plotA[:,1] 是 Y 轴

PlotB = 
array([[1, 7],
       [2, 7],
       [3, 7],
       [4, 7]])

其中 plotB[:,0] 是 X 轴,plotB[:,1] 是 Y 轴

加入的数组是:

PlotsAB = 
array([[1, n, 7],
       [2, 5, 7],
       [3, 5, 7],
       [4, n, 7],
       [5, 5, n]])

在哪里 PlotAB[:,0]是连接的X轴(排序uniuq)。

plotAB[:,1] 是 PlotA 的 Y 轴。

plotAB[:,2] 是 PlotB 的 Y 轴。

'n' 表示缺少值的地方 - 此图中不存在。

顺便说一句,我需要这个来为 dygraphs 绘图仪 (http://dygraphs.com/gallery/#g/independent-series)

编写数据

请指教, 谢谢。

这是一个解决方案,它使用 numpy.setdiff1d 在每个输入数组中查找唯一的 x 元素,并使用 numpy.argsort 在插入 [x, NaN] 元素后对输入数组进行排序他们。

import numpy as np

def join_op(a,b):
    ax = a[:,0]
    bx = b[:,0]

    # elements unique to b
    ba_x = np.setdiff1d(bx,ax)

    # elements unique to a
    ab_x = np.setdiff1d(ax,bx)

    ba_y = np.NaN*np.empty(ba_x.shape)
    ab_y = np.NaN*np.empty(ab_x.shape)

    ba = np.array((ba_x,ba_y)).T
    ab = np.array((ab_x,ab_y)).T

    a_new = np.concatenate((a,ba))
    b_new = np.concatenate((b,ab))

    a_sort_idx = np.argsort(a_new[:,0])
    b_sort_idx = np.argsort(b_new[:,0])

    a_new_sorted = a_new[a_sort_idx]
    b_new_sorted = b_new[b_sort_idx]

    b_new_sorted_y = b_new_sorted[:,1].reshape(-1,1)

    return np.concatenate((a_new_sorted,b_new_sorted_y),axis=1)

a = np.array([[2,5],[3,5],[5,5]])
b = np.array([[1,7],[2,7],[3,7],[4,7]])
c = combine(a,b)

输出:

[[  1.  nan   7.]
 [  2.   5.   7.]
 [  3.   5.   7.]
 [  4.  nan   7.]
 [  5.   5.  nan]]