Python: Removing Matrix columns that contain NaN

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


As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles