如何从pandas python中另一个数据帧的子集交集中减去一个数据帧
发布时间:2020-12-20 12:34:49 所属栏目:Python 来源:网络整理
导读:我在 python中有以下数据帧: 数据帧1 1 2 3 4 5dog 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 0fox 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 1jumps dog 0 0 0 0 0 fox 0 1 0 1 1 jumps 0
我在
python中有以下数据帧:
数据帧1 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 数据帧2 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 您可以看到dataframe2包含dataframe1的多索引,但它还包含其他多索引,如马和猫.数据帧2也不包含数据帧1的所有列,因为您可以看到它错过了第3列. 我想从数据帧1中减去数据帧2,使得该函数仅减去两者中常见的数据并忽略其余数据,结果数据帧的形状为数据帧2. 有没有人知道pandas是否提供了内置的方法,或者我是否需要自己构建一个函数.如果是这样,你能指出我正确的方向吗?任何建议都非常感谢.谢谢. 注意:这个问题类似于我发布here的另一个问题,除了我不想比较这些,而是??想要进行减法的算术运算. 解决方法
我相信你只想要这样的东西:
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. 编辑 哎呀,你真的想要df1 – df2,但是df2的形状,有点棘手,因为那时fillna(df1)会阻止我们放弃正确的行,但是,你可以使用乘以-1! 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |