[Python] Using pd.Dataframe.replace with an apply function as the replace value

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have several dataframes that have mixed in some columns with dates in this ASP.NET format "/Date(1239018869048)/". I've figured out how to parse this into python's datetime format for a given column. However I would like to put this logic into a function so that I can pass it any dataframe and have it replace all the dates that it finds that match a regex using pd.Dataframe.replace.

    something like:

    def pretty_dates():
    #Messy logic here

    df.replace(to_replace=r'\/Date(d+)', value=pretty_dates(df), regex=True)


    Problem with this is that the df that is being passed to pretty_dates is the whole dataframe not just the cell that is needed to be replaced.

    So the concept I'm trying to figure out is if there is a way that the value that should be replaced when using df.replace can be a function instead of a static value.

    Thank you so much in advance

    EDIT To try to add some clarity, I have many columns in a dataframe, over a hundred that contain this date format. I would like not to list out every single column that has a date. Is there a way to apply the function the clean my dates across all the columns in my dataset? So I do not want to clean 1 column but all the hundreds of columns of my dataframe.

    Continue reading...

Compartilhe esta Página