我有一个已标准化为1的浮点数数组(即数组中的最大数为1),我想将其用作图的颜色索引。在使用matplotlib使用灰度时,这需要使用0到1之间的字符串,所以我希望将浮点数组转换为字符串数组。我试图通过使用"astype('str')“来实现这一点,但这似乎创建了一些与原始值不同(甚至接近)的值。
我注意到这一点是因为matplotlib抱怨在数组中找到数字8,这很奇怪,因为它被规范化为1!
简而言之,我有一个float64的数组phis,这样:
numpy.where(phis.astype('str').astype('float64') != phis)
不是空的。这令人费解,因为(希望是天真的)它似乎是numpy中的一个bug,有没有什么我可能做错了的事情导致了这一点?
编辑:经过调查,这似乎是由于字符串函数处理高精度浮点数的方式造成的。使用矢量化的toString函数(如来自robbles答案),也是这种情况,但是,如果λ函数是:
lambda x: "%.2f" % x
然后,作图工作--越来越好奇。(但是,显然数组不再相等!)
发布于 2011-03-20 07:14:03
如果你有一个numbers
数组,并且你想要一个strings
数组,你可以这样写:
strings = ["%.2f" % number for number in numbers]
如果您的数字是浮点数,则数组将是一个数组,该数组的数字与带有两个小数的字符串相同。
>>> a = [1,2,3,4,5]
>>> min_a, max_a = min(a), max(a)
>>> a_normalized = [float(x-min_a)/(max_a-min_a) for x in a]
>>> a_normalized
[0.0, 0.25, 0.5, 0.75, 1.0]
>>> a_strings = ["%.2f" % x for x in a_normalized]
>>> a_strings
['0.00', '0.25', '0.50', '0.75', '1.00']
请注意,它也适用于numpy
数组:
>>> a = numpy.array([0.0, 0.25, 0.75, 1.0])
>>> print ["%.2f" % x for x in a]
['0.00', '0.25', '0.50', '0.75', '1.00']
如果您有一个多维数组,则可以使用类似的方法:
new_array = numpy.array(["%.2f" % x for x in old_array.reshape(old_array.size)])
new_array = new_array.reshape(old_array.shape)
示例:
>>> x = numpy.array([[0,0.1,0.2],[0.3,0.4,0.5],[0.6, 0.7, 0.8]])
>>> y = numpy.array(["%.2f" % w for w in x.reshape(x.size)])
>>> y = y.reshape(x.shape)
>>> print y
[['0.00' '0.10' '0.20']
['0.30' '0.40' '0.50']
['0.60' '0.70' '0.80']]
如果你查看Matplotlib example for the function you are using,你会注意到他们使用了类似的方法:构建空矩阵,并用插值方法构建的字符串填充它。引用代码的相关部分为:
colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
for x in range(xlen):
colors[x, y] = colortuple[(x + y) % len(colortuple)]
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
linewidth=0, antialiased=False)
发布于 2011-03-20 07:29:04
这可能比您想要的要慢,但您可以这样做:
>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)
它看起来像是在从float64转换为字符串时对值进行四舍五入,但是通过这种方式,您可以随心所欲地定制转换。
发布于 2011-03-20 18:07:51
如果主要问题是从浮点型转换为字符串时的精度损失,一种可能的方法是将浮点型转换为decimal
S:http://docs.python.org/library/decimal.html。
在Python2.7和更高版本中,您可以直接将浮点数转换为decimal
对象。
https://stackoverflow.com/questions/5365520
复制相似问题