3

我正在使用布尔数组从 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
4

1 回答 1

4

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

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.

于 2013-01-26T13:07:48.320 回答