Python 使用一行代码比较来自不同数据帧的两个索引后生成 True False 输出



我有两个数据框,如下所示

small_df =

index    data1
2         123
3         436

big_df =

index    data1
0          78
1          67
2          13
3          46

我想比较检查是否有任何small_df索引存在于使用一行代码的big_df并生成真或假。 我的代码:

big_idx  = [True for i in small_df.index if i in big_df.index]

我目前的输出

big_idx = [True True]

我的预期输出

big_idx = [False False True True]

如何在我的代码中插入 False?我尝试遵循代码但没有成功。

[True for i in small_df.index if i in big_df.index else False]

最后一行可以相当容易地修复:

all(i in big_df.index for i in small_df.index)

但是,有一个更好的方法:

small_df.index.difference(big_df.index)

这将从不在big_df中的small_df返回索引元素。只需检查其长度是否为零即可。

[True if i in small_df.index else False for i in big_df.index]

将索引转换为列表,然后设置为设置,然后使用交集。

A= set(small_df.index.tolist())
B= set(bid_df.index.tolist())
print(len(A.intersection(B)) > 0)

最新更新