使用布尔数组从列表中删除项目

时间:2013-01-26 13:05:34

标签: python list

我正在使用布尔数组从numpy数组中删除一些列。是否可以用列表做类似的事情?

#Set a numpy array of booleans to True if column datatype is "Categorical"
cols_to_remove = np.array([datatype == "Categorical" for datatype in datatypes])

#Make a new array without the "Categorical" columns
cat_data = data[:, -cols_to_remove] # data here is a 2D numpy array

#Trying to do the same for a list - this way doesn't work
cat_datatypes = datatypes[-cols_to_remove] # datatypes here is a 1D list

1 个答案:

答案 0 :(得分:2)

这可以通过列表理解来完成:

In [17]: cols_to_remove = [False, False, True, False, True, False]

In [18]: [d for (d, remove) in zip(datatypes, cols_to_remove) if not remove]
Out[18]: ['a', 'b', 'd', 'f']

cols_to_remove是索引数组,可以使用以下解决方案:

In [12]: datatypes = ['a', 'b', 'c', 'd', 'e', 'f']

In [13]: cols_to_remove = [2, 4]

In [14]: [d for (i, d) in enumerate(datatypes) if i not in cols_to_remove]
Out[14]: ['a', 'b', 'd', 'f']

此处,出于效率原因,将cols_to_remove转换为set可能是个好主意。