remove a list if nan is in a list of lists

Removing values from list

Using filter

nan isnt proper Python syntax and is only used in the Pandas library. So I am going to replace this value with None.

we can use a filter function to remove any values within the list that contains a nan value.

test = list(filter(lambda x: None not in x, test))

Using list comprehension

Edit: Should be x instead of test. Thanks @fountainhead

test = [x for x in test if None not in test]

test = [x for x in test if None not in x]

Both will return a list with values not containing None in them

Plotting

We can use a library called matplotlib to plot a graph. For example, to create a scatter plot:

import matplotlib.pyplot as plt
plt.scatter(x, y)

where plt.scatter takes in x values and y values for row and columns respectively. The full code is as follows:

import matplotlib.pyplot as plt

test = [[1,2],[1,None],[3,4]]
test = list(filter(lambda x: None not in x, test))

x = [x for x,y in test]
y = [y for x,y in test]

# Assume all first elements are x values second elements are y values
plt.scatter(x, y)
plt.show()

The example images is as follows

enter image description here

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top