使用索引查找Pandas中两个系列之间的交集



我有两个不同长度的序列,我正试图根据索引找到这两个序列的交集,其中索引是一个字符串。最终的结果是,希望是一个序列,它具有基于公共字符串索引的交集元素。

有什么想法吗?

Pandas索引有一个可以使用的交集方法。如果您有两个系列,s1s2,则

s1.index.intersection(s2.index)

或者,等效地:

s1.index & s2.index

提供了s1s2中的索引值。

然后,您可以使用此索引列表来查看序列的相应元素。例如:

>>> ixs = s1.index.intersection(s2.index)
>>> s1.loc[ixs]
# subset of s1 with only the indexes also found in s2 appears here

我的两个数据都是递增的,所以我写了一个函数来获取索引,然后根据索引过滤数据。

np.shape(data1)  # (1330, 8)
np.shape(data2)  # (2490, 9)
index_1, index_2 = overlap(data1, data2)
data1 = data1[index1]
data2 = data2[index2]
np.shape(data1)  # (540, 8)
np.shape(data2)  # (540, 9)
def overlap(data1, data2):
    '''both data is assumed to be incrementing'''
    mask1 = np.array([False] * len(data1))
    mask2 = np.array([False] * len(data2))
    idx_1 = 0
    idx_2 = 0
    while idx_1 < len(data1) and idx_2 < len(data2):
        if data1[idx_1] < data2[idx_2]:
            mask1[idx_1] = False
            mask2[idx_2] = False
            idx_1 += 1
        elif data1[idx_1] > data2[idx_2]:
            mask1[idx_1] = False
            mask2[idx_2] = False
            idx_2 += 1
        else:
            mask1[idx_1] = True
            mask2[idx_2] = True
            idx_1 += 1
            idx_2 += 1
    return mask1, mask2

最新更新