[Python] Checking if value is in a dataframe column in python

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list of ids (docids), and I have a dataframe with ids and associated columns (entity, gender).

    I need to check if x id from the list of ids is in the dataframe id column.

    If x is in the dataframe, I then want the string from the 'gender' column. I am checking first to avoid a key error when I iterate through my list of ids, as some of the IDs are not in the dataframe.

    My list of ids is (abbreviated) docids = [1,2]

    Dataframe gdf:

    docid entity Gender Gender Probability Gender Count
    0 0 david l. aagesen male 1.00 3489607
    1 1 robert t. aangeenbrug male 1.00 1566661


    The following code returns false, even though I have confirmed docids[1] (the value of which is 1) is in the docid column:

    docids[1] in gdf['docid'].values


    Whereas this code returns true which is accurate.

    1 in gdf['docid'].values


    When I run this code, I get an empty series, but when I run it with 1 instead of docids[1] I get the actual row of data:

    gdf[(gdf['docid'] == docids[1])]


    This is how I am trying to use in the future. Right now, when I run the code, it returns false on every ID and results in 3 empty lists.

    mids = [] # male IDs
    fids = [] # female ids
    uids = [] # unknown

    for d in docids:

    intd = int(d)

    if d in gdf['docid'].values == True:

    row = gdf[(gdf['docid'] == intd)]
    gender = row.iloc[0]['Gender']

    if gender == 'male':
    mids.append(intd)

    elif gender == 'female':
    fids.append(intd)

    else:
    uids.append(intd)

    Continue reading...

Compartilhe esta Página