[Python] Replace values in series with first regex group if found, if not leave nan

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

  1. Stack

    Stack Membro Participativo

    Say I have a dataframe such as

    df = pd.DataFrame(data = {'col1': [1,np.nan, '>3', 'NA'], 'col2':["3.","<5.0",np.nan, 'NA']})


    out:
    col1 col2
    0 1 3.
    1 NaN <5.0
    2 >3 NaN
    3 NA NA


    What I would like is to strip stuff like "<" or ">", and get to floats only

    out:
    col1 col2
    0 1 3.
    1 NaN 5.0
    2 3 NaN
    3 NaN NaN


    I thought about something like

    df['col2'].replace({'.*' : r"[-+]?(?:\d*\.*\d+)"}, regex=True, inplace=True)


    the idea being, replace anything with the regex for float, (I think), but this fails

    error: bad escape \d at position 8


    I tried along the lines of

    df['col2'].replace({r"[-+]?(?:\d*\.*\d+)": r"\1"}, regex=True, inplace=True)


    assuming ">"or "<" come before the float number, but then this fails (does not catch anything) if the field is a string or np.nan.

    Any suggestions please?

    Continue reading...

Compartilhe esta Página