[Python] How to convert a pandas dataframe to numeric future proof?

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    Until now I used to convert all values in a pandas dataframe with combined numerical and string entries to numeric values if possible in one easy step, using .map and .to_numeric with "errors = 'ignore'".

    It worked perfectly, but after updating to the latest version of Pandas (2.2.3) I get a FutureWarning.

    import pandas as pd
    A = pd.DataFrame({
    'x' : ['1','2','3'],
    'y' : ['not_a_number','5',9999],
    }) # example data
    B = A.map(pd.to_numeric, errors = 'ignore')

    # FutureWarning: errors='ignore' is deprecated and will raise in a future version. Use to_numeric without passing errors and catch exceptions explicitly instead B = A.map(pd.to_numeric, errors = 'ignore')


    How could I code this future proof in an elegant, vectorised way?

    I could not think of any solution that is not very cumbersome (looping over each individual entry of the dataframe).

    Continue reading...

Compartilhe esta Página