有没有一种Pythonic的方法来获取数据框之间的差异?

4

给定这两个数据框:

A = pd.DataFrame([[1, 5, 2, 8, 2], [2, 4, 4, 20, 2], [3, 3, 1, 20, 2], [4, 2, 2, 1, 0], 
              [5, 1, 4, -5, -4], [1, 5, 2, 2, -20], [2, 4, 4, 3, 0], [3, 3, 1, -1, -1], 
              [4, 2, 2, 0, 0], [5, 1, 4, 20, -2]],
             columns=["A", "B", "C", "D", "E"],
             index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

B = pd.DataFrame([[1, 5, 2, 8, 2], [2, 4, 4, 20, 2], [3, 3, 1, 20, 2], [4, 2, 2, 1, 0]],
             columns=["A", "B", "C", "D", "E"],
             index=[1, 2, 3, 4])

有没有一种Pythonic的方式来获取C = A - B,并使输出为:
    A   B   C    D    E
5   5   1   4   -5   -4
6   1   5   2    2  -20
7   2   4   4    3    0
8   3   3   1   -1   -1
9   4   2   2    0    0
10  5   1   4   20   -2
2个回答

5
如果索引有意义,您可以基于索引进行子集操作:
A[~A.index.isin(B.index)]

enter image description here


有趣,'~'符号是什么? - hernanavella
1
这是用于否定的。在布尔序列中将 true -> false,false -> true 进行转换。 - Psidom
1
@hernanavella 按位运算符被重载,以在 "pandas" 数据结构上执行 逐元素布尔运算 - juanpa.arrivillaga
1
@hernanavella 尝试一下 (A.A == A.B) & (A.D == A.E)。请注意,由于位运算符仍具有相同的优先级,因此通常需要使用括号。 - juanpa.arrivillaga

4

编辑 更改答案,使用基于 .loc 的索引而不是 .ix

您可以使用指数的对称差异来索引 A。pandas 指数大多像 set 一样运作!

In [11]: A.loc[A.index.symmetric_difference(B.index)]
Out[11]:
    A  B  C   D   E
5   5  1  4  -5  -4
6   1  5  2   2 -20
7   2  4  4   3   0
8   3  3  1  -1  -1
9   4  2  2   0   0
10  5  1  4  20  -2

或者你只是想要 difference,这相当于在不相交的情况下的对称差:

In [17]: A.loc[A.index.difference(B.index)]
Out[17]:
    A  B  C   D   E
5   5  1  4  -5  -4
6   1  5  2   2 -20
7   2  4  4   3   0
8   3  3  1  -1  -1
9   4  2  2   0   0
10  5  1  4  20  -2

您也可以直接使用大多数重载的set运算符:

In [18]: A.loc[A.index & B.index] # intersection 
Out[18]:
   A  B  C   D  E
1  1  5  2   8  2
2  2  4  4  20  2
3  3  3  1  20  2
4  4  2  2   1  0

In [19]: A.loc[A.index | B.index] # union
Out[19]:
    A  B  C   D   E
1   1  5  2   8   2
2   2  4  4  20   2
3   3  3  1  20   2
4   4  2  2   1   0
5   5  1  4  -5  -4
6   1  5  2   2 -20
7   2  4  4   3   0
8   3  3  1  -1  -1
9   4  2  2   0   0
10  5  1  4  20  -2

In [20]: A.loc[A.index ^  B.index] # disjunctive union, i.e. symmetric difference and XOR 
Out[20]:
    A  B  C   D   E
5   5  1  4  -5  -4
6   1  5  2   2 -20
7   2  4  4   3   0
8   3  3  1  -1  -1
9   4  2  2   0   0
10  5  1  4  20  -2

1
很不幸,ix正在被弃用,对吧? - hernanavella
@hernanavella 我之前没有听说过这个...但你可以随时使用 loc - juanpa.arrivillaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接