根据公共索引过滤两个数据帧

时间:2016-06-20 20:18:54

标签: python-3.x pandas

您好我有两个数据帧。他们有一些共同的指数。我想将两个原始日期帧转换为两个仅包含公共索引的新日期帧。你能帮助我实现这个目标吗?这是一个例子。

     df1 = pd.DataFrame({'one' : pd.Series([1,3,5], index=['a', 'b', 'c']),
   ....:                    'two' : pd.Series([2,4,6], index=['a', 'b', 'c']),
   ....:                    'three' : pd.Series([-4,-3,-2], index=['a','b', 'c'])});
df2=pd.DataFrame({'x' : pd.Series([1,3,5], index=['b', 'c', 'd']),
   ....:                    'y' : pd.Series([2,4,6], index=['b', 'c', 'd']),
   ....:                    'z' : pd.Series([-3,-2,-1], index=['b', 'c', 'd'])});
print(df1)
print(df2)

所以你可以看到df1和df2如下。

    one  three  two
a    1     -4    2
b    3     -3    4
c    5     -2    6
   x  y  z
b  1  2 -3
c  3  4 -2
d  5  6 -1

我希望看到它们变得像

    one  three  two

b    3     -3    4
c    5     -2    6
   x  y  z
b  1  2 -3
c  3  4 -2

2 个答案:

答案 0 :(得分:0)

您可以使用.join()

df1.join(df2, how='inner')[df1.columns]

   one  three  two
b    3     -3    4
c    5     -2    6

答案 1 :(得分:0)

我会将Index.intersectionboolean indexing结合使用:

In [73]: mask = df1.index.intersection(df2.index)

In [77]: df1 = df1.ix[mask]

In [78]: df2 = df2.ix[mask]

In [79]: df1
Out[79]:
   one  three  two
b    3     -3    4
c    5     -2    6

In [80]: df2
Out[80]:
   x  y  z
b  1  2 -3
c  3  4 -2

或者您可以使用isin() fution:

In [81]: df1[df1.index.isin(df2.index)]
Out[81]:
   one  three  two
b    3     -3    4
c    5     -2    6

In [82]: df2[df2.index.isin(df1.index)]
Out[82]:
   x  y  z
b  1  2 -3
c  3  4 -2
相关问题