这里是python新手。我已经编写了解决问题的代码。然而,应该有一种更好的方法。
我有两个系列来自同一个表,但由于一些早期的过程,我得到了独立的集合。(由于条目属于同一记录,它们可以再次连接到单个数据帧中)
Ser1 Ser2 | id | | section | | ---| |-------- | | 1 | | A | | 2 | | B | | 2 | | C | | 3 | | D | df2 | id | section | | ---|---------| | 1 | A | | 2 | B | | 2 | Z | | 2 | Y | | 4 | X |
首先,我想在Ser1中查找与df2中相同id匹配的条目。然后,检查是否在df2My预期结果的节列中找不到ser2中的值:
| id | section | result | | ---|-------- |---------| | 1 | A | False | # Both id(1) and section(A) are also in df2 | 2 | B | False | # Both id(2) and section(B) are also in df2 | 2 | C | True | # id(2) is in df2 but section(C) is not | 3 | D | False | # id(3) is not in df2, in that case the result should also be True
我的代码:
for k, v in Ser2.items(): rslt_df = df2[df2['id'] == Ser[k]] if rslt_df.empty: print(False) if(v not in rslt_df['section'].tolist()): print(True) else: print(False)
我知道代码不是很好。但是在阅读了关于合并和理解列表的内容后,我很困惑改进它的最佳方法是什么。如果能提供任何帮助,我将不胜感激。谢谢!