7

我有一个看起来像这样的数组:

k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None), 
                 (1.2, 0.003), (0.99, 0.004)])

我想绘制不是的值(None, None)并保留数组值的索引。也就是说,我想要一个(None, None)有价值的地方。

完成后,我想绘制

y = k[:,0] + k[:,1]

但我什至不能将数组加在一起。k我尝试屏蔽数组,但我丢失了原始数组的索引值。

一个最小的例子:

import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

# I'd like to plot
#     k[:,0] + k[:,1]
# but I can't add None

# Here I get rid of the (None, None) values so I can add
# But I lose the original indexing
mask = k != (None, None)
y = k[mask].reshape((-1,2))

ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')
4

2 回答 2

8

您可以使用 numpy.nan 而不是 None。

import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (numpy.nan, numpy.nan), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')

或者您也可以屏蔽 x 值,因此 x 和 y 之间的索引是一致的

import matplotlib.pyplot as pyplot
import numpy

x = range(5)
y = numpy.array([(1.,0.001), (1.1, 0.002), (numpy.nan, numpy.nan), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()


ax.plot(range(len(y)), y[:,0]+y[:,1], 'k--')
import matplotlib.pyplot as pyplot
import numpy

x = range(5)
k = numpy.array([(1.,0.001), (1.1, 0.002), (None, None), 
                 (1.2, 0.003), (0.99, 0.004)])

Fig, ax = pyplot.subplots()

# This plots a gap---as desired
ax.plot(x, k[:,0], 'k-')

# I'd like to plot
#     k[:,0] + k[:,1]
# but I can't add None

arr_none = np.array([None])
mask = (k[:,0] == arr_none) | (k[:,1] == arr_none)

ax.plot(numpy.arange(len(y))[mask], k[mask,0]+k[mask,1], 'k--')
于 2013-10-29T14:41:12.970 回答
1

你可以过滤你的数组:

test = np.array([None])
k = k[k!=test].reshape(-1, 2).astype(float)

然后总结列并制作情节。您的方法的问题是您没有将None类型转换为 numpy 数组,这不允许正确创建掩码。

于 2013-10-29T15:12:51.023 回答