【问题标题】:Is there a pythonic way to obtain the difference between dataframes?有没有一种pythonic方法来获取数据帧之间的差异?
【发布时间】:2017-08-17 19:28:13
【问题描述】:

鉴于这两个数据框:

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

【问题讨论】:

    标签: python python-3.x pandas dataframe subset


    【解决方案1】:

    编辑 将答案更改为使用基于 .loc 的索引而不是 .ix 您可以使用索引的对称差异来索引 A。pandas 索引也大多像 sets 一样!

    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
    

    【讨论】:

    • 很遗憾 ix 已被弃用,不是吗?
    • @hernanavella 我没听说过……但你总是可以使用loc
    【解决方案2】:

    如果索引有意义,您可以根据索引进行子集化:

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

    【讨论】:

    • 有趣,'~' 符号是什么?
    • 用于否定。在布尔系列中转换 true -> false, false -> true。
    • @hernanavella 位运算符被重载以对pandas 数据结构执行元素布尔运算
    • @hernanavella just try (A.A == A.B) & (A.D == A.E) 注意,因为位运算符仍然具有相同的优先级,您通常必须使用括号
    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多