[Python] Creating a loop to append df values to excel and skip values that already exist in...

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

  1. Stack

    Stack Membro Participativo

    I currently have a df with two columns (one column with an alias and the other with full name). I am able to append the df values to the Excel sheet I want and save the sheet down with the values but I can't figure out a loop to skip over appending values that already exist in the sheet.

    For example if I run my code and column A ('xyz') and column B ('abc') gets appended to my Excel sheet, the next time I run my code I don't want to write another row in the sheet, I need the loop to skip values that were already appended and only write new column values that doesn't already exist in the Excel sheet.

    Below is the code i have so far which successfully appends the dataframe values to my excel sheet but cant figure out how to skip over values that already exist.

    df1 = pd.DataFrame(columns=['alias','fullname']

    excelpath = 'contact.xlsx'
    A = load_workbook(excelpath)
    B = A['Sheet1']

    for r in dataframe_to_rows(df1, index = False):
    B.append(r)
    A.save(excelpath)


    Ideally I would like the loop to iterate over the first column of my dataframe and check if that data is in the Excel sheet in a specific column, if it's not there, then add column A and B to the Excel sheet, but if it already exists, skip over that value and move onto the next one.

    Continue reading...

Compartilhe esta Página