문제

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.]])

어떻게 할 수 있습니까?

도움이 되었습니까?

해결책

그 이름을 감안할 때 표준 방식은 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) 또는 Row-Wise (axis = 0) 작동 삭제.

다른 팁

예제 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]])

또 다른 방법은 마스킹 어레이를 사용하는 것입니다.

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 메소드는 NANS와 INF가 마스킹 된 마스크 배열을 반환합니다.

print(np.ma.masked_invalid(a))
[[-- 2.0 3.0 --]
 [1.0 2.0 3.0 9.0]]

np.ma.compress_cols 메소드는 마스크 된 값이 포함 된 모든 열로 2D 배열을 반환합니다.

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

보다마스크 시드 array 조작

이것은 열이없는 다른 배열을 만듭니다.

  b = a.compress(logical_not(z), axis=1)

에서 Numpy Documentation

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])

귀하의 상황에서는 원하는 데이터를 다음과 같이 추출 할 수 있습니다.

a[:, -z]

"-z"는 부울 배열 "z"의 논리적 부정입니다. 이것은 다음과 같습니다.

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

>>> A = A.transpose()

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

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.]]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top