[Python] Unable to write lookup output to Pandas dataframe using append loop

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    I want to lookup one array in dataframe using pandas (or anything else) and if the value is found in that column of dataframe then corresponding value in another column of same dataframe is picked up with both recorded into another dataframe.

    For example, here, lookup column is:

    arg_array = [111, 222, 333, 444, 777 , 1089 , 3562 ]

    I know arg_array[1] = lookup_id = 111 exists so that corresponding value (id_number) is recored. But here 1089 and 3562) do not exist so NAN recored.

    The dataframe array should be:

    Lookup item Corresponding item
    111 OK
    222 OK
    333 OK
    444 OK
    777 OK
    1089 NAN
    3562 NAN

    It operates using loop - really it's replacing a VLOOKUP so its a vlookup/append but cant get the append to work in a fresh df.

    I can get the print to work off the loop so left as that but really need help on appending empty dataframe ('new_df').

    e.g.:

    arg_array = arr.array('i', [111, 222, 333, 444, 777 , 1089 , 3562 ])
    new_df = []

    for item in arg_array:
    lookup_id = item

    id_number = get_score_by_id(df_past, lookup_id)
    if id_number is not None:
    print(f'{lookup_id}, {id_number}')

    else:
    print('NAN')


    Or should it be something like this where

    arg_array = arr.array('i', [111, 222, 333, 444, 777 , 1089 , 3562 ])
    new_df = []

    for item in arg_array:
    lookup_id = item

    id_number = get_score_by_id(df_past, lookup_id)
    if id_number is not None:
    df_append = (f'{lookup_id}, {id_number}')

    else:
    df_append = ('NAN')

    print(df_append)



    Where I've added in : df_append

    Thanks.

    Continue reading...

Compartilhe esta Página