python-3.x 如何通过另一个 Dataframe 的行来过滤一个 Dataframe ?

rdlzhqv9  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(148)

我有两个 Dataframe :DF1:

id          type
"a"      "alpha"
"a"      "alpha"
"a"      "beta"
"a"      "gamma"

和DF2:

id          type          
"a"      "alpha"         
"a"      "alpha"         
"a"      "alpha"          
"a"      "alpha"          
"a"      "beta"           
"a"      "beta"

对于DF1中的每一行,如果它们具有相同的“id”和“type”,则我想要从DF2中移除单个行。

id          type          
"a"      "alpha"         
"a"      "alpha"          
"a"      "beta"

我怎么能这么做?

nwnhqdif

nwnhqdif1#

您可以使用collection.Counter从df2中减去df1的元素,然后重建 Dataframe :

from collections import Counter
cols = ['id', 'type']
diff = Counter(zip(*df2[cols].T.values)) - Counter(zip(*df1[cols].T.values))
pd.DataFrame([k for k,v in diff.items() for _ in range(v)], columns=cols)

输出:

id     type
0  "a"  "alpha"
1  "a"  "alpha"
2  "a"   "beta"

编辑:为了模块化稍微重构代码

相关问题