[Python] How to fill blanks in dataframe1 with values from dataframe2 (with pandas)?

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

  1. Stack

    Stack Membro Participativo

    After some process, I got two dataframes, df1 is main frame which has some blanks in it, df2 has values that df1 missing. I used the code bellow, it should be able to fill all the blanks, but it doesn't fill any blank.

    df4.update(postcode_match)


    some blanks in df4:
    [​IMG]

    values in postcode_match:
    [​IMG]

    Values of last two columns in df2 should be fill in df1 last two columns. Why didn't it behave as expected?

    I have tried .combine_first, it filled blanks and merged rows of those two dataframes.

    I also tried:

    for col in ['Latitude', 'Longitude']:
    df4.loc[postcode_match.index, col] = postcode_match[col]


    'Latitude' and 'Longitude' are indexes of the last columns, it also don't work.

    This can achieve results I expected, but I want to use pandas' function to solve it. Is there any way can achieve it?

    Latitude_dict = postcode_match.set_index('Postcode')['Latitude'].to_dict()
    Longitude_dict = postcode_match.set_index('Postcode')['Longitude'].to_dict()

    df4['Latitude'] = df4['Latitude'].fillna(df4['Postcode'].map(Latitude_dict))
    df4['Longitude'] = df4['Longitude'].fillna(df4['Postcode'].map(Longitude_dict))

    Continue reading...

Compartilhe esta Página