如何在numpy.array中删除列

103

我想删除numpy.array中选择的列。我这样做:

n [397]: a = array([[ NaN,   2.,   3., NaN],
   .....:        [  1.,   2.,   3., 9]])

In [398]: print a
[[ NaN   2.   3.  NaN]
 [  1.   2.   3.   9.]]

In [399]: z = any(isnan(a), axis=0)

In [400]: print z
[ True False False  True]

In [401]: delete(a, z, axis = 1)
Out[401]:
 array([[  3.,  NaN],
       [  3.,   9.]])
在这个例子中,我的目标是删除所有包含NaN的列。我期望最后一个命令的结果为:
array([[2., 3.],
       [2., 3.]])

我该怎么做?

8个回答

168

从它的名字来看,标准方式应该是delete

import numpy as np

A = np.delete(A, 1, 0)  # delete second row of A
B = np.delete(B, 2, 0)  # delete third row of B
C = np.delete(C, 1, 1)  # delete second column of C
根据 NumPy 文档页面numpy.delete 函数的参数如下: numpy.delete(arr, obj, axis=None) 其中:
- arr 指输入数组, - obj 指要删除的子数组(例如列 / 行编号或数组的片段), - axis 指要进行操作的轴,可选行或列。 若要在列上删除,则 axis = 1;若要在行上删除,则 axis = 0

14
我认为你应该参考numpy,而不是scipy。http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html - hlin117
6
将数组(array)、索引(index)和轴(axis)作为参数加入即可。 - maximus

32

来自numpy文档的示例:

>>> a = numpy.array([[ 0,  1,  2,  3],
               [ 4,  5,  6,  7],
               [ 8,  9, 10, 11],
               [12, 13, 14, 15]])

>>> numpy.delete(a, numpy.s_[1:3], axis=0)                       # remove rows 1 and 2

array([[ 0,  1,  2,  3],
       [12, 13, 14, 15]])

>>> numpy.delete(a, numpy.s_[1:3], axis=1)                       # remove columns 1 and 2

array([[ 0,  3],
       [ 4,  7],
       [ 8, 11],
       [12, 15]])

@alvas 这里有一个组织良好的解释!https://dev59.com/yVwY5IYBdhLWcg3wYm4B - Daeyoung
1
@Alvas ,s_是:一种更好的为数组构建索引元组的方法.:https://docs.scipy.org/doc/numpy/reference/generated/numpy.s_.html - Minions

16

另一种方法是使用掩码数组:

import numpy as np
a = np.array([[ np.nan,   2.,   3., np.nan], [  1.,   2.,   3., 9]])
print(a)
# [[ NaN   2.   3.  NaN]
#  [  1.   2.   3.   9.]]
np.ma.masked_invalid方法返回一个掩码数组,其中的NaN和inf都被掩盖了:
print(np.ma.masked_invalid(a))
[[-- 2.0 3.0 --]
 [1.0 2.0 3.0 9.0]]

np.ma.compress_cols方法返回一个2-D数组,其中包含任何包含蒙版值的列被抑制:

a=np.ma.compress_cols(np.ma.masked_invalid(a))
print(a)
# [[ 2.  3.]
#  [ 2.  3.]]

请参阅操作掩码数组


9
这将创建另一个没有这些列的数组:
  b = a.compress(logical_not(z), axis=1)

2
很酷。我希望Matlab的语法在这里也能用:“a(:,z) = []”更简单。 - Boris Gorelik
1
@bpowah:确实。更一般的方法是 b = a[:,z]。你可能想相应地更新你的答案。 - Boris Gorelik

8

来自Numpy文档

np.delete(arr, obj, axis=None) 返回一个删除了沿轴的子数组的新数组。

>>> arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

>>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])

6
在您的情况下,您可以使用以下方法提取所需数据:
a[:, -z]

"

"-z"是布尔数组“z”的逻辑否定。这与以下内容相同:

"
a[:, logical_not(z)]

2
>>> A = array([[ 1,  2,  3,  4],
               [ 5,  6,  7,  8],
               [ 9, 10, 11, 12]])

>>> A = A.transpose()

>>> A = A[1:].transpose()

-1
删除包含NaN的矩阵列。 这是一个冗长的答案,但希望易于理解。
def column_to_vector(matrix, i):
    return [row[i] for row in matrix]
import numpy
def remove_NaN_columns(matrix):
    import scipy
    import math
    from numpy import column_stack, vstack

    columns = A.shape[1]
    #print("columns", columns)
    result = []
    skip_column = True
    for column in range(0, columns):
        vector = column_to_vector(A, column)
        skip_column = False
        for value in vector:
            # print(column, vector, value, math.isnan(value) )
            if math.isnan(value):
                skip_column = True
        if skip_column == False:
            result.append(vector)
    return column_stack(result)

### test it
A = vstack(([ float('NaN'), 2., 3., float('NaN')], [ 1., 2., 3., 9]))
print("A shape", A.shape, "\n", A)
B = remove_NaN_columns(A)
print("B shape", B.shape, "\n", B)

A shape (2, 4) 
 [[ nan   2.   3.  nan]
 [  1.   2.   3.   9.]]
B shape (2, 2) 
 [[ 2.  3.]
 [ 2.  3.]]

我其实不太明白你的意思。这段代码是怎么工作的? - RamenChef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接