﻿ 如何从pandas python中另一个数据帧的子集交集中减去一个数据帧？ - 代码日志

#### 如何从pandas python中另一个数据帧的子集交集中减去一个数据帧？

``````             1  2  3  4  5
dog   dog    0  1  1  0  1
fox    1  0  0  0  0
jumps  0  0  0  1  0
over   1  0  1  0  1
the    0  1  0  0  0
fox   dog    0  0  1  1  1
fox    0  0  0  0  0
jumps  0  0  1  0  1
over   0  1  0  0  0
the    0  0  0  1  1
jumps dog    0  0  0  0  0
fox    0  1  0  1  1
jumps  0  0  0  0  1
over   1  0  1  0  0
the    0  0  0  0  0
over  dog    0  0  1  0  0
fox    0  1  0  1  1
jumps  0  0  0  0  0
over   0  1  0  1  0
the    1  0  1  0  0
the   dog    0  0  1  0  0
fox    0  0  0  0  1
jumps  0  1  0  0  0
over   0  0  1  1  0
the    0  1  1  0  1
``````

``````             1  2  4  5
dog   dog    1  0  0  0
fox    0  1  0  1
jumps  0  1  1  0
the    0  0  0  0
horse  1  0  1  0
fox   dog    0  0  0  0
fox    0  1  0  1
over   0  0  0  0
the    0  1  0  1
cat    0  0  1  0
``````

``````In [23]: (df2 - df1.drop('3', axis=1)).fillna(df2).dropna()
Out[23]:
1    2    4    5
dog dog    1.0 -1.0  0.0 -1.0
fox   -1.0  1.0  0.0  1.0
horse  1.0  0.0  1.0  0.0
jumps  0.0  1.0  0.0  0.0
the    0.0 -1.0  0.0  0.0
fox cat    0.0  0.0  1.0  0.0
dog    0.0  0.0 -1.0 -1.0
fox    0.0  1.0  0.0  1.0
over   0.0 -1.0  0.0  0.0
the    0.0  1.0 -1.0  0.0
``````

Pandas已经自动在索引上对齐,这是它的神奇之处,但你只需要智能地填充/删除nans.

``````In [25]: (df2 - df1.drop('3', axis=1)).fillna(df2).dropna() * -1
Out[25]:
1    2    4    5
dog dog   -1.0  1.0 -0.0  1.0
fox    1.0 -1.0 -0.0 -1.0
horse -1.0 -0.0 -1.0 -0.0
jumps -0.0 -1.0 -0.0 -0.0
the   -0.0  1.0 -0.0 -0.0
fox cat   -0.0 -0.0 -1.0 -0.0
dog   -0.0 -0.0  1.0  1.0
fox   -0.0 -1.0 -0.0 -1.0
over  -0.0  1.0 -0.0 -0.0
the   -0.0 -1.0  1.0 -0.0
``````

``````In [31]: (-df2 + df1.drop('3', axis=1)).fillna(-df2).dropna()
Out[31]:
1    2    4    5
dog dog   -1.0  1.0  0.0  1.0
fox    1.0 -1.0  0.0 -1.0
horse -1.0  0.0 -1.0  0.0
jumps  0.0 -1.0  0.0  0.0
the    0.0  1.0  0.0  0.0
fox cat    0.0  0.0 -1.0  0.0
dog    0.0  0.0  1.0  1.0
fox    0.0 -1.0  0.0 -1.0
over   0.0  1.0  0.0  0.0
the    0.0 -1.0  1.0  0.0
``````