【发布时间】:2023-01-31 04:54:14
【问题描述】:
我有两个要比较的独立 df 帧:
f1
P53-Malat1
Neat1-Malat1
Gap1-Malat1
和 f2:
intA,intB
P53-Malat1,Neat1-Malat1
Gap1-Malat1,Malat1-Pias3
我想遍历 f2 中每一列的行,并查看它在 f1 中的 id。如果是,则打印该行+“找到”,如果否,则在单独的列中打印该行+“not_found”。
f2 中的第二列也是如此。
我试过这种方法但它不起作用 - 我错过了什么吗?
with open("f1.txt","r") as f1:
content = f1.read().splitlines()
#print(content)
f2 = pd.read_csv("f2.csv")
f2["col1_search"] = f2.apply(lambda x: x["intA"]+"_found" if x in content else x["intA"]+"_not_found", axis=1)
f2["col2_search"] = f2.apply(lambda x: x["intB"]+"_found" if x in content else x["intB"]+"_not_found", axis=1)
所以所需的输出应该是这种格式的 f2 :
col1_search,col2_search
P53-Malat1_found,Neat1-Malat1_found
Gap1-Malat1_found,Malat1-Pias3_not_found
谢谢你。
【问题讨论】:
-
对于这样的事情,你最好的选择可能是使用像 np.where(condition, if_true_this, if_false_this) 这样的东西。如果您可以更改答案以将数据复制到 df 中,我认为您可以获得更多帮助。
标签: python pandas dataframe lambda