检查 python 中的文件内容中是否存在 pandas 数据框中的任何行值

问题描述 投票:0回答:1

我有一个名为 df 的数据框,它有一个包含多行的 ID 列。我正在读取一个文件,并希望快速检查我的数据帧的 ID 列中的任何 ID 是否在文件内容中。以下是我目前正在做的事情。它有效,但我确信有一种更有效的方法来检查文件中是否存在数据帧列中的任何行。

    # Read in and store file contents
    file = open('myfile.txt', 'r')
    contents = file.read()

    # Loop through each ID in the ID column and look for it in the file
    for id in df['ID']:
        if id in contents:
            print(f"found {id}")
python pandas dataframe list
1个回答
0
投票

也许

df.isin()
(文档这里)会有用?然后,您可以创建一个新列,它是每个 ID 是否在文件中的布尔掩码。

df["id_found"] = df['ID'].isin(contents)
© www.soinside.com 2019 - 2024. All rights reserved.