【问题标题】:Get intersecting (common) indexes across two 2D (or 3D) numpy arrays [duplicate]跨两个 2D(或 3D)numpy 数组获取相交(公共)索引
【发布时间】:2017-05-04 01:13:33
【问题描述】:

我有来自两个不同目录的数据,我想使用坐标来匹配这两个目录。我拥有的数据是来自目录 1 的x1,y1,z1,a1,b1,c1,etc(大约 50 万个元素)和来自目录 2 的x2,y2,z2,a2,e2,m2,n2,etc(大约百万个元素)。我要做的是首先构建一个包含 (x,y) 的二维数组) 坐标,如有必要,我将扩展到 (x,y,z),并比较二维数组以找到相同的元素。

co1 = np.vstack((x1,y1)).T
co2 = np.vstack((x2,y2)).T

idx1 = np.in1d(co1,co2)   # not working for 2D arrays
idx2 = np.in1d(co2,co1)

np.savetxt('combined_data.txt',np.c_[x1[idx1],y1[idx1],a1[idx1],e2[idx2],n2[idx2]],fmt='%1.4f   %1.4f   %1.4f   %1.4f   %1.4f')

例如,我有以下数据集:

x1 = np.array([1,2,3,4,5])
y1 = np.array([5,4,3,2,1])
x2 = np.array([1,4,6,2,6,4,8,9,3])
y2 = np.array([5,1,5,3,6,2,8,3,3])

(1,5), (3,3), (4,2) are the common coordinates between the two catalogs. Therefore,

idx1 = [Ture, False, True, True, False], idx2 = [True, False, False, False, False, True, False, False, True]. 

但问题是np.in1d 是一个1D 例程,它不能应用于2D 或3D 数组。任何人都知道一些 numpy 例程来完成这项任务?

【问题讨论】:

  • scipy.spatial.cKDTree 将为您提供快速的 n 最近邻查找...
  • Stack with : xy1 = np.column_stack((x1,y1)); xy2 = np.column_stack((x2,y2)) 然后使用 dup 目标链接列出的方法来获取行索引,当索引到要搜索的数组中时,应该会为您提供所需的 o/p。跨度>

标签: python arrays numpy multidimensional-array compare


【解决方案1】:

将两个数组都转换为 pandas 数据帧:

df1 = pd.DataFrame({"x" : x1, "y" : y1})).reset_index()

合并它们:

result = pd.merge(df1, df2, left_on=["x","y"], right_on=["x","y"])
#   index_x  x  y  index_y
#0        0  1  5        0
#1        2  3  3        8
#2        3  4  2        5

并获取索引:

result[["index_x","index_y"]]
#   index_x  index_y
#0        0        0
#1        2        8
#2        3        5

【讨论】:

  • 谢谢。实际上我需要每个数组的索引。我尝试添加left_index = Trueright_index = True,但pd.merge 返回一些错误。你知道如何解决它吗?
  • 创建数据框时,在末尾添加对.reset_index()的调用。这会将当前索引复制到单独的列中。
  • 我试过了,它似乎返回了一些错误:ValueError: Big-endian buffer not supported on little-endian compiler。我已经对df1 = pd.DataFrame({"x" : np.array(ra_sdss).byteswap().newbyteorder(), "y" : np.array(dec_sdss).byteswap().newbyteorder()}).reset_index() 这样的坐标进行了更改。我认为这个错误是由记忆引起的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多