array python 交集_python-数组之间的交集索引

这篇博客介绍了如何使用numpy库在数组中找到并处理唯一值的索引。通过示例展示了如何对数组排序,使用`argsort`、`searchsorted`和`split`函数来找到插入独特值的正确位置,并返回这些值在原始数组中的索引。这种方法适用于处理已排序和未排序的数据。最后,博客提供了一个名为`ix_intersection`的函数,用于通用的索引查找操作。
摘要由CSDN通过智能技术生成

这是向量化的解决方案:

import numpy as np

startRavel = np.array([1,2,2,2,3,3])

unique_policies = np.array([1,2,3])

使用np.argsort对startRavel进行排序.

ix = np.argsort(startRavel)

s_startRavel = startRavel[ix]

使用np.searchsorted查找应该在startRavel中插入unique_policies以保持顺序的索引:

s_ix = np.searchsorted(s_startRavel, unique_policies)

# array([0, 1, 4])

然后使用np.split使用获得的索引拆分数组. s_ix再次使用np.argsort来处理未排序的输入:

ix_r = np.argsort(s_ix)

ixs = np.split(ix, s_ix[ix_r][1:])

np.array(ixs)[ix_r]

# [array([0]), array([1, 2, 3]), array([4, 5])]

?通用解决方案:

让我们将其包装在一个函数中:

def ix_intersection(x, y):

"""

Finds the indices where each unique

value in x is found in y.

Both x and y must be numpy arrays.

----------

x: np.array

Must contain unique values.

Values in x are assumed to be in y.

y: np.array

Returns

-------

Array of arrays. Each array contains the indices where a

value in x is found in y

"""

ix_y = np.argsort(y)

s = np.searchsorted(y[ix_y], x)

ix_r = np.argsort(s)

ixs = np.split(ix_y, s[ix_r][1:])

return np.array(ixs)[ix_r]

?其他例子

让我们尝试以下数组:

startRavel = np.array([1,3,3,2,2,2])

unique_policies = np.array([1,2,3])

ix_intersection(unique_policies, startRavel)

# array([array([0]), array([3, 4, 5]), array([1, 2])])

另一个例子,这次输入未排序:

startRavel = np.array([1,3,3,2,2,2,5])

unique_policies = np.array([1,2,5,3])

ix_intersection(unique_policies, startRavel)

# array([array([0]), array([3, 4, 5]), array([6]), array([1, 2])])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值