我正在尝试编写将数组中的整数转换为给定基数的代码,并对其进行填充以使它们具有相同的大小.我从 numpy.vectorize 时,Alex Martelli>"> stackoverflow 无效,尽管它适用于单个数组:
I am trying to make a code that converts integers in array to a given base and padding them to make them from the same size. The following code which I manipulated from a code on stackoverflow by Alex Martelli, doesn't work when I apply numpy.vectorize on it, although it works for single arrays:
def int2base(x, base,size): ret=np.zeros(size) if x==0: return ret digits = [] while x: digits.append(x % base) x /= base digits.reverse() ret[size-len(digits):]=digits[:] return ret vec_int2base=np.vectorize(int2base) vec_int2base(np.asarray([2,1,5]),base=3,size=3)哪个终止并出现以下错误:
Which terminates with the following error:
... 1640 if ufunc.nout == 1: 1641 _res = array(outputs, -> 1642 copy=False, subok=True, dtype=otypes[0]) 1643 else: 1644 _res = tuple([array(_x, copy=False, subok=True, dtype=_t) ValueError: setting an array element with a sequence.有没有更好的方法可以为vectors案例编写代码,而我在这里缺少什么呢?
Is there any better way to write it for vectors case, and what am I missing here.
推荐答案以下是矢量化版本:
import numpy as np def int2base(x, base, size=None, order='decreasing'): x = np.asarray(x) if size is None: size = int(np.ceil(np.log(np.max(x))/np.log(base))) if order == "decreasing": powers = base ** np.arange(size - 1, -1, -1) else: powers = base ** np.arange(size) digits = (x.reshape(x.shape + (1,)) // powers) % base return digits如果 x 的形状为 shp ,则结果的形状为 shp +(大小).如果未给出 size ,则该大小基于 x 中的最大值. order 确定数字的顺序;使用 order ="decreasing" (默认值)将123转换为[1、2、3].使用 order ="increasing" 获得[3,2,1].(后者可能更自然,因为结果中数字的索引与该数字的基数幂相匹配.)
If x has shape shp, the result has shape shp + (size,). If size is not given, the size is based on the largest value in x. order determines the order of the digits; use order="decreasing" (the default) to convert, say, 123 to [1, 2, 3]. Use order="increasing" to get [3, 2, 1]. (The latter might be more natural, as the index of the digit in the result matches the power of the base for that digit.)
示例:
In [97]: int2base([255, 987654321], 10) Out[97]: array([[0, 0, 0, 0, 0, 0, 2, 5, 5], [9, 8, 7, 6, 5, 4, 3, 2, 1]]) In [98]: int2base([255, 987654321], 10, size=12) Out[98]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 5], [0, 0, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1]]) In [99]: int2base([255, 987654321], 10, order="increasing") Out[99]: array([[5, 5, 2, 0, 0, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8, 9]]) In [100]: int2base([255, 987654321], 16) Out[100]: array([[ 0, 0, 0, 0, 0, 0, 15, 15], [ 3, 10, 13, 14, 6, 8, 11, 1]])更多推荐
整数数组的基本转换
发布评论