如果你想数学运算适用于就地一个numpy的数组,你可以简单地使用标准就地运营商
+=,
-=,
/=等,因此,例如:
>>> def foo(a):... a += 10... >>> a = numpy.arange(10)>>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])>>> foo(a)>>> aarray([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
这些 *** 作的就地版本启动起来有点快,特别是对于较大的阵列:
>>> def normalize_inplace(array, imin=-1, imax=1):... dmin = array.min()... dmax = array.max()... array -= dmin... array *= imax - imin... array /= dmax - dmin... array += imin... >>> def normalize_copy(array, imin=-1, imax=1):... dmin = array.min()... dmax = array.max()... return imin + (imax - imin) * (array - dmin) / (dmax - dmin)... >>> a = numpy.arange(10000, dtype='f')>>> %timeit normalize_inplace(a)10000 loops, best of 3: 144 us per loop>>> %timeit normalize_copy(a)10000 loops, best of 3: 146 us per loop>>> a = numpy.arange(1000000, dtype='f')>>> %timeit normalize_inplace(a)100 loops, best of 3: 12.8 ms per loop>>> %timeit normalize_copy(a)100 loops, best of 3: 16.4 ms per loop
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)