[Python] Slicing data frame with datetime columns (Python - Pandas)

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

  1. Stack

    Stack Membro Participativo

    Through the loc and iloc methods, Pandas allows us to slice dataframes. Still, I am having trouble to do this when the columns are datetime objects.

    For instance, suppose the data frame generated by the following code:

    d = {'col1': [1], 'col2': [2],'col3': [3]}
    df = pd.DataFrame(data=d)
    dates = ['01-01-2001','02-02-2002','03-03-2003']
    dates = pd.to_datetime(dates).date
    df.columns= dates


    [​IMG]

    Let us try to slice the first two columns of the dataframe through dfloc:

    df.loc[0,'01-01-2001':'02-02-2002']


    We get the following TypeError:'<' not supported between instances of 'datetime.date' and 'str'

    How could this be solved?

    Continue reading...

Compartilhe esta Página