[Python] How can I use sklearn's make_column_selector to select all valid datetime columns?

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

  1. Stack

    Stack Membro Participativo

    I want to select columns based on their datetime data types. My DataFrame has for example columns with types np.dtype('datetime64[ns]'), np.datetime64 and 'datetime64[ns, UTC]'.

    Is there a generic way to select all columns with a datetime datatype?


    For instance, this works:

    from sklearn.compose import make_column_selector
    selector = make_column_selector(dtype_include=(np.dtype('datetime64[ns]'),np.datetime64))
    selected_columns = selector(df)


    But this doesn't (datatype from a pandas df with 'UTC'):

    from sklearn.compose import make_column_selector
    selector = make_column_selector(dtype_include=np.dtype('datetime64[ns, UTC]')
    selected_columns = selector(df)


    Compared to numeric data types where you can simply use np.number instead of np.int64 etc.

    API-Reference to make_column_selector: LINK

    Continue reading...

Compartilhe esta Página