gpt4 book ai didi

python - Pandas 删除不在标签中的行

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:14 24 4
gpt4 key购买 nike

我有两个具有重叠索引的 Pandas DataFrame(A 和 B)。我想删除 DataFrame B 中 DataFrame A 中不存在该索引值的行。

我调查了 Pandas drop DataFrames 的方法,但它会删除具有给定标签的列,我想删除没有给定标签的列。

现在我设法做到了:

B.drop(B.drop(A.index).index)

但这显然不是最好的方法(效率低或可读性差)。有没有更好的办法?

示例:

数据框A:

   index       col1  
1 some_data
2 some_data
3 some_data
4 some_data

数据框B:

   index       col2  
1 other_data
2 other_data
3 other_data
4 other_data
5 other_data
6 other_data

我要获取DataFrame B':

   index       col2  
1 other_data
2 other_data
3 other_data
4 other_data

最佳答案

我想你可以使用 isinboolean indexing :

print B.index.isin(A.index)
[ True True True True False False]

print B[B.index.isin(A.index)]
col2
index
1 other_data
2 other_data
3 other_data
4 other_data

关于python - Pandas 删除不在标签中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36768525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com