【发布时间】:2014-12-07 05:18:22
【问题描述】:
我有两个不同长度的系列,我试图根据索引找到两个系列的交集,其中索引是一个字符串。希望最终结果是一个系列,其中包含基于公共字符串索引的交集元素。
有什么想法吗?
【问题讨论】:
标签: python pandas intersection series
我有两个不同长度的系列,我试图根据索引找到两个系列的交集,其中索引是一个字符串。希望最终结果是一个系列,其中包含基于公共字符串索引的交集元素。
有什么想法吗?
【问题讨论】:
标签: python pandas intersection series
Pandas 索引有一个intersection method,您可以使用它。如果你有两个系列,s1 和 s2,那么
s1.index.intersection(s2.index)
或者,等效地:
s1.index & s2.index
为您提供s1 和s2 中的索引值。
然后,您可以使用此索引列表来查看系列的相应元素。例如:
>>> ixs = s1.index.intersection(s2.index)
>>> s1.loc[ixs]
# subset of s1 with only the indexes also found in s2 appears here
【讨论】:
s1 = pd.Series(range(3)) 和s2 = pd.Series(range(3), index=[5, 0, 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
【讨论】: