Removing Matrix columns that contain NaN. This is a lengthy answer, but hopefully easy to follow.
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.]]
No comments:
Post a Comment