【问题标题】:Finding the intersection between two series in Pandas using index使用索引在 Pandas 中查找两个系列之间的交集
【发布时间】:2014-12-07 05:18:22
【问题描述】:

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

有什么想法吗?

【问题讨论】:

    标签: python pandas intersection series


    【解决方案1】:

    Pandas 索引有一个intersection method,您可以使用它。如果你有两个系列,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
    

    【讨论】:

    • 很好,但它只给了我索引,而不是带有值的系列。
    • 我尝试了这个函数,将它分配给一个变量,但它什么也没给我。我确信有共同的元素,但到目前为止还没有。
    • 试过 common = s1.index.intersection(s2.index);打印 len(common) 给出 0.
    • @Boss1295 看起来您的两个系列中没有任何共同的索引值。如果您尝试使用s1 = pd.Series(range(3))s2 = pd.Series(range(3), index=[5, 0, 2]),您应该会看到该方法按预期工作。
    • s1.index & s2.index 做类似的工作。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多