我有2个Pandas系列对象,它们都是常见的多索引DF的子集。
示例:
// SeriesA =
Session Movie # Point in Time
Session A mov1 1932 0.300000
1934 0.133333
1936 0.166667
1938 0.316667
// SeriesB =
Session Movie # Point in Time
Session A mov1 1932 0.300000
1934 0.133333
1940 0.200000
1942 0.083333
1944 0.133333
Session B mov1 1932 0.500000
我正在尝试提取在SeriesA和SeriesB中都存在三个索引级别的行。
因此,对于上面的示例数据,正确的结果将是
expected = [('Session A', 'mov1', 1932), ('Session A', 'mov1', 1934)]
我尝试使用numy的intersect1d()和pandas的交集()函数,但是都返回一个元组列表,其中每个元组都是其中一个索引标签的所有现有选项。
result = [('Session A', Session B'), ('mov1'), (1932, 1934, 1936, 1938, 1940, 1942, 1944)]
我可以逐行进行迭代,但这似乎很浪费。我不知道任何神奇的解决方案吗?
答案 0 :(得分:0)
我的Index.intersection
输出正确:
a = SeriesA.index.intersection(SeriesB.index).tolist()
print (a)
[('Session A', 'mov1', 1932), ('Session A', 'mov1', 1934)]
merge
的另一个想法:
c = ['Session','Movie #','Point in Time']
a = (SeriesA.reset_index()
.merge(SeriesB.reset_index(), on=c)
.set_index(c)
.index
.tolist())
print (a)
[('Session A', 'mov1', 1932), ('Session A', 'mov1', 1934)]