Is there a pythonic way to get the difference between a data frame?

Given these 2 data frames:

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])

Is there a pythonic way to get C = A - B, and the output would be:

    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
+4
source share
2 answers

If the index makes sense, you can subset based on the index:

A[~A.index.isin(B.index)]

enter image description here

+5
source

Change the modified response to using indexing .locinstead. .ix You can use the symmetric index difference for index A. pandasIndexes basically act like that settoo!

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
+4

Source: https://habr.com/ru/post/1673153/


All Articles