Question

I have three equal-length arrays named ra, ma and op with mostly numbers and few instances when they have 'nan' or 'None' in place of a number. Eg:

ra = [0, 1, 2, nan, 8 , 3, 8, 5]
ma = [3, nan, 5, 8, 9, 6, 4, 10]
op = [7, None, 7, 9, 3, 6, None, 7]

I want to make a 3d plot of the numbers in them. My code is :

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(ra,ma,op)

plt.show()

Everything is fine till I type plt.show() - then it gives me a long list of error which ends like:

"TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType'".

May be: It is because of the nan values, but i do not know how to remove them :-/ if i want to remove the nan value from ra (which is the 4th value of list), i will also have to remove the respective 4th values from ma and op. And I can not figure out how to do that or if at all we need to do that.

Can someone please point out where i am going wrong??

Était-ce utile?

La solution

You could get rid of columns withNonein them like this (in either Python 2.7 or 3+):

from __future__ import print_function
try:
    from itertools import izip
except ImportError:
    izip = zip

ra = [0, 1, 2, float('nan'), 8 , 3, 8, 5]
ma = [3, float('nan'), 5, 8, 9, 6, 4, 10]
op = [7, None, 7, 9, 3, 6, None, 7]

ra, ma, op = izip(*(col for col in izip(ra, ma, op) if None not in col))

print('ra =', ra)
print('ma =', ma)
print('op =', op)

Output:

ra = (0, 2, nan, 8, 3, 5)
ma = (3, 5, 8, 9, 6, 10)
op = (7, 7, 9, 3, 6, 7)

As @Bakuriu mentioned in a comment, it might be a better to use thecompress()function which is in the built-initertoolsmodule and is therefore likely to be faster. It also eliminates the relatively slow linear search through each column of values in the above.

from itertools import compress
ra, ma, op =  izip(*compress(izip(ra, ma, op), (x is not None for x in op)))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top