[Python] Is there a way to filter columns of a pandas dataframe which include elements of a...

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

  1. Stack

    Stack Membro Participativo

    In the below dataframe I would like to filter the columns based on a list called 'animals' to select all the columns that include the list elements.

    animal_data = {
    "date": ["2023-01-22","2023-11-16","2024-06-30","2024-08-16","2025-01-22"],
    "cats_fostered": [1,2,3,4,5],
    "cats_adopted":[1,2,3,4,5],
    "dogs_fostered":[1,2,3,4,5],
    "dogs_adopted":[1,2,3,4,5],
    "rabbits_fostered":[1,2,3,4,5],
    "rabbits_adopted":[1,2,3,4,5]
    }

    animals = ["date","cat","rabbit"]

    animal_data = {
    "date": ["2023-01-22","2023-11-16","2024-06-30","2024-08-16","2025-01-22"],
    "cats_fostered": [1,2,3,4,5],
    "cats_adopted":[1,2,3,4,5],
    "rabbits_fostered":[1,2,3,4,5],
    "rabbits_adopted":[1,2,3,4,5]
    }


    I have tried some approaches below but they either don't work with lists or return no columns as it is looking for an exact match with 'cats' or 'rabbits' and not just columns that contain the strings

    animal_data[animal_data.columns.intersection(animals)] # returns an empty df
    animal_data.filter(regex=animals) # returns an error: not able to use regex with a list

    Continue reading...

Compartilhe esta Página