Select Columns by Masking Using Itertools Compress and a Filter List
In this example we use compress from itertools to select columns in a dataframe by using a filter list of boolean values as a mask. Here we've manually defined the filter list but this could be derived in other ways such as through a recursive feature elimination algorithm.
The original dataframe has four columns but only the 1st, 3rd and 4th columns will be kept.
from itertools import compress filter_list = [True, False, True, True] cols = compress(df.columns, filter_list) cols = list(cols) df.columns = cols
By detro - Last Updated Dec. 6, 2021, 6:53 p.m.