GVKun编程网logo

Python numpy 模块-ma() 实例源码(python中numpy模块)

5

如果您对Pythonnumpy模块-ma()实例源码感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Pythonnumpy模块-ma()实例源码的详细内容,我们还将为您解答p

如果您对Python numpy 模块-ma() 实例源码感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Python numpy 模块-ma() 实例源码的详细内容,我们还将为您解答python中numpy模块的相关问题,并且为您提供关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的有价值信息。

本文目录一览:

Python numpy 模块-ma() 实例源码(python中numpy模块)

Python numpy 模块-ma() 实例源码(python中numpy模块)

Python numpy 模块,ma() 实例源码

我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用numpy.ma()

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def timer(s, v='''', nloop=500, nrep=3):
  2. units = ["s", "ms", "µs", "ns"]
  3. scaling = [1, 1e3, 1e6, 1e9]
  4. print("%s : %-50s : " % (v, s), end='' '')
  5. varnames = ["%ss,nm%ss,%sl,nm%sl" % tuple(x*4) for x in ''xyz'']
  6. setup = ''from __main__ import numpy,ma,%s'' % '',''.join(varnames)
  7. Timer = timeit.Timer(stmt=s, setup=setup)
  8. best = min(Timer.repeat(nrep, nloop)) / nloop
  9. if best > 0.0:
  10. order = min(-int(numpy.floor(numpy.log10(best)) // 3), 3)
  11. else:
  12. order = 3
  13. print("%d loops,best of %d: %.*g %s per loop" % (nloop, nrep,
  14. 3,
  15. best * scaling[order],
  16. units[order]))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def timer(s,
  2. units[order]))
项目:pygeotools    作者:dshean    | 项目源码 | 文件源码
  1. def fn_getma(fn, bnum=1):
  2. """Get masked array from input filename
  3.  
  4. Parameters
  5. ----------
  6. fn : str
  7. Input filename string
  8. bnum : int,optional
  9. Band number
  10.  
  11. Returns
  12. -------
  13. np.ma.array
  14. Masked array containing raster values
  15. """
  16. #Add check for filename existence
  17. ds = fn_getds(fn)
  18. return ds_getma(ds, bnum=bnum)
  19.  
  20. #Given input dataset,return a masked array for the input band
项目:pygeotools    作者:dshean    | 项目源码 | 文件源码
  1. def ds_getma(ds, bnum=1):
  2. """Get masked array from input GDAL Dataset
  3.  
  4. Parameters
  5. ----------
  6. ds : gdal.Dataset
  7. Input GDAL Datset
  8. bnum : int,optional
  9. Band number
  10.  
  11. Returns
  12. -------
  13. np.ma.array
  14. Masked array containing raster values
  15. """
  16. b = ds.GetRasterBand(bnum)
  17. return b_getma(b)
  18.  
  19. #Given input band,return a masked array
项目:pygeotools    作者:dshean    | 项目源码 | 文件源码
  1. def b_getma(b):
  2. """Get masked array from input GDAL Band
  3.  
  4. Parameters
  5. ----------
  6. b : gdal.Band
  7. Input GDAL Band
  8.  
  9. Returns
  10. -------
  11. np.ma.array
  12. Masked array containing raster values
  13. """
  14. b_ndv = get_ndv_b(b)
  15. #bma = np.ma.masked_equal(b.ReadAsArray(),b_ndv)
  16. #This is more appropriate for float,handles precision issues
  17. bma = np.ma.masked_values(b.ReadAsArray(), b_ndv)
  18. return bma
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def timer(s,
  2. units[order]))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def timer(s,
  2. units[order]))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def timer(s,
  2. units[order]))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_testPut(self):
  2. # Test of put
  3. with suppress_warnings() as sup:
  4. sup.filter(
  5. np.ma.core.MaskedArrayFutureWarning,
  6. "setting an item on a masked array which has a "
  7. "shared mask will not copy")
  8. d = arange(5)
  9. n = [0, 0, 1, 1]
  10. m = make_mask(n)
  11. x = array(d, mask=m)
  12. self.assertTrue(x[3] is masked)
  13. self.assertTrue(x[4] is masked)
  14. x[[1, 4]] = [10, 40]
  15. self.assertTrue(x.mask is not m)
  16. self.assertTrue(x[3] is masked)
  17. self.assertTrue(x[4] is not masked)
  18. self.assertTrue(eq(x, [0, 10, 2, -1, 40]))
  19.  
  20. x = array(d, mask=m)
  21. x.put([0, 2], [-1, 100, 200])
  22. self.assertTrue(eq(x, 200, 0]))
  23. self.assertTrue(x[3] is masked)
  24. self.assertTrue(x[4] is masked)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def timer(s,
  2. units[order]))
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def timer(s,
  2. units[order]))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
  5. self.assertTrue(isinstance(ma + na, MaskedArray))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'', ''arctanh'', ''arcsin'', ''arccos'',
  4. ''arccosh'', ''log'', ''log10'', ''divide'',
  5. ''true_divide'', ''floor_divide'', ''remainder'', ''fmod'']
  6. for f in [''sqrt'', ''exp'', ''conjugate'',
  7. ''sin'', ''cos'', ''tan'',
  8. ''arcsin'', ''arctan'',
  9. ''sinh'', ''cosh'', ''tanh'',
  10. ''arcsinh'',
  11. ''arccosh'',
  12. ''arctanh'',
  13. ''absolute'', ''fabs'', ''negative'',
  14. ''floor'', ''ceil'',
  15. ''logical_not'',
  16. ''add'', ''subtract'', ''multiply'',
  17. ''divide'', ''true_divide'',
  18. ''remainder'', ''fmod'', ''hypot'', ''arctan2'',
  19. ''equal'', ''not_equal'', ''less_equal'', ''greater_equal'',
  20. ''less'', ''greater'',
  21. ''logical_and'', ''logical_or'', ''logical_xor'']:
  22. try:
  23. uf = getattr(umath, f)
  24. except AttributeError:
  25. uf = getattr(fromnumeric, f)
  26. mf = getattr(np.ma, f)
  27. args = self.d[:uf.nin]
  28. with np.errstate():
  29. if f in f_invalid_ignore:
  30. np.seterr(invalid=''ignore'')
  31. if f in [''arctanh'', ''log10'']:
  32. np.seterr(divide=''ignore'')
  33. ur = uf(*args)
  34. mr = mf(*args)
  35. self.assertTrue(eq(ur.filled(0), mr.filled(0), f))
  36. self.assertTrue(eqmask(ur.mask, mr.mask))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def compare_functions_1v(func,
  2. xs=xs, nmxs=nmxs, xl=xl, nmxl=nmxl):
  3. funcname = func.__name__
  4. print("-"*50)
  5. print("%s on small arrays" % funcname)
  6. module, data = "numpy.ma", "nmxs"
  7. timer("%(module)s.%(funcname)s(%(data)s)" % locals(), v="%11s" % module, nloop=nloop)
  8.  
  9. print("%s on large arrays" % funcname)
  10. module, "nmxl"
  11. timer("%(module)s.%(funcname)s(%(data)s)" % locals(), nloop=nloop)
  12. return
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def compare_methods(methodname, args, vars=''x'', test=True,
  2. xs=xs, nmxl=nmxl):
  3. print("-"*50)
  4. print("%s on small arrays" % methodname)
  5. data, ver = "nm%ss" % vars, ''numpy.ma''
  6. timer("%(data)s.%(methodname)s(%(args)s)" % locals(), v=ver, nloop=nloop)
  7.  
  8. print("%s on large arrays" % methodname)
  9. data, ver = "nm%sl" % vars, nloop=nloop)
  10. return
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'', mr.mask))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def compare_functions_1v(func, nloop=nloop)
  2. return
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def compare_methods(methodname, nloop=nloop)
  2. return
项目:pygeotools    作者:dshean    | 项目源码 | 文件源码
  1. def ds_getma_sub(src_ds, bnum=1, scale=None, maxdim=1024.):
  2. """Load a subsampled array,rather than full resolution
  3.  
  4. This is useful when working with large rasters
  5.  
  6. Uses buf_xsize and buf_ysize options from GDAL ReadAsArray method.
  7.  
  8. Parameters
  9. ----------
  10. ds : gdal.Dataset
  11. Input GDAL Datset
  12. bnum : int,optional
  13. Band number
  14. scale : int,optional
  15. Scaling factor
  16. maxdim : int,optional
  17. Maximum dimension along either axis,in pixels
  18.  
  19. Returns
  20. -------
  21. np.ma.array
  22. Masked array containing raster values
  23. """
  24. #print src_ds.GetFileList()[0]
  25. b = src_ds.GetRasterBand(bnum)
  26. b_ndv = get_ndv_b(b)
  27. ns, nl = get_sub_dim(src_ds, scale, maxdim)
  28. #The buf_size parameters determine the final array dimensions
  29. b_array = b.ReadAsArray(buf_xsize=ns, buf_ysize=nl)
  30. bma = np.ma.masked_values(b_array, b_ndv)
  31. return bma
  32.  
  33. #Note: need to consolidate with warplib.writeout (takes ds,not ma)
  34. #Add option to build overviews when writing GTiff
  35. #Input proj must be WKT
项目:pygeotools    作者:dshean    | 项目源码 | 文件源码
  1. def replace_ndv(b, new_ndv):
  2. b_ndv = get_ndv_b(b)
  3. bma = np.ma.masked_values(b.ReadAsArray(), b_ndv)
  4. bma.set_fill_value(new_ndv)
  5. b.WriteArray(bma.filled())
  6. b.SetNoDataValue(new_ndv)
  7. return b
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'',
  4. # ''nonzero'',''around'',
  5. # ''sometrue'',''alltrue'', mr.mask))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def compare_functions_1v(func, nloop=nloop)
  2. return
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def compare_methods(methodname, nloop=nloop)
  2. return
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'', mr.mask))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def compare_functions_1v(func, nloop=nloop)
  2. return
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def compare_methods(methodname, nloop=nloop)
  2. return
项目:deepgestures_lasagne    作者:nneverova    | 项目源码 | 文件源码
  1. def _get_stblock(self, data_input, hnd, mdlt, start_frame=None):
  2. goodness = False
  3. if start_frame is None:
  4. start_frame = random.randint(0, len(data_input[''min_length''])-self.step*(self.nframes-1)-1)
  5. stblock = numpy.zeros([self.nframes, self.block_size, self.block_size])
  6. for ii in xrange(self.nframes):
  7. v = data_input[hnd][mdlt][start_frame + ii * self.step]
  8. mm = abs(numpy.ma.maximum(v))
  9. if mm > 0.:
  10. # normalize to zero mean,unit variance,
  11. # concatenate in spatio-temporal blocks
  12. stblock[ii] = self.prenormalize(v)
  13. goodness = True
  14. return stblock, goodness
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'', mr.mask))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def compare_functions_1v(func, nloop=nloop)
  2. return
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def compare_methods(methodname, nloop=nloop)
  2. return
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'', mr.mask))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def compare_methods(methodname, nloop=nloop)
  2. return
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def compare_functions_2v(func,
  2. ys=ys, nmys=nmys,
  3. xl=xl, nmxl=nmxl,
  4. yl=yl, nmyl=nmyl):
  5. funcname = func.__name__
  6. print("-"*50)
  7. print("%s on small arrays" % funcname)
  8. module, "nmxs,nmys"
  9. timer("%(module)s.%(funcname)s(%(data)s)" % locals(), "nmxl,nmyl"
  10. timer("%(module)s.%(funcname)s(%(data)s)" % locals(), nloop=nloop)
  11. return
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_testMixedArithmetic(self):
  2. na = np.array([1])
  3. ma = array([1])
  4. self.assertTrue(isinstance(na + ma, MaskedArray))
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_testUfuncRegression(self):
  2. f_invalid_ignore = [
  3. ''sqrt'', mr.mask))
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def compare_functions_1v(func, nloop=nloop)
  2. return
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def compare_methods(methodname, nloop=nloop)
  2. return
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_testcopySize(self):
  2. # Tests of some subtle points of copying and sizing.
  3. with suppress_warnings() as sup:
  4. sup.filter(
  5. np.ma.core.MaskedArrayFutureWarning,
  6. "setting an item on a masked array which has a "
  7. "shared mask will not copy")
  8.  
  9. n = [0, 0]
  10. m = make_mask(n)
  11. m2 = make_mask(m)
  12. self.assertTrue(m is m2)
  13. m3 = make_mask(m, copy=1)
  14. self.assertTrue(m is not m3)
  15.  
  16. x1 = np.arange(5)
  17. y1 = array(x1, mask=m)
  18. self.assertTrue(y1._data is not x1)
  19. self.assertTrue(allequal(x1, y1._data))
  20. self.assertTrue(y1.mask is m)
  21.  
  22. y1a = array(y1, copy=0)
  23. self.assertTrue(y1a.mask is y1.mask)
  24.  
  25. y2 = array(x1, mask=m, copy=0)
  26. self.assertTrue(y2.mask is m)
  27. self.assertTrue(y2[2] is masked)
  28. y2[2] = 9
  29. self.assertTrue(y2[2] is not masked)
  30. self.assertTrue(y2.mask is not m)
  31. self.assertTrue(allequal(y2.mask, 0))
  32.  
  33. y3 = array(x1 * 1.0, mask=m)
  34. self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype)
  35.  
  36. x4 = arange(4)
  37. x4[2] = masked
  38. y4 = resize(x4, (8,))
  39. self.assertTrue(eq(concatenate([x4, x4]), y4))
  40. self.assertTrue(eq(getmask(y4), 0]))
  41. y5 = repeat(x4, (2, 2), axis=0)
  42. self.assertTrue(eq(y5, 3, 3]))
  43. y6 = repeat(x4, y6))
项目:unmixing    作者:arthur-e    | 项目源码 | 文件源码
  1. def composite(reducers, *rasters, normalize=''sum'', nodata=-9999.0, dtype=np.float32):
  2. ''''''
  3. NOTE: Uses masked arrays in NumPy and therefore is MUCH slower than the
  4. `composite2()` function,which is equivalent in output.
  5.  
  6. Creates a multi-image (multi-date) composite from input rasters. The
  7. reducers argument specifies,in the order of the bands (endmembers),how
  8. to pick a value for that band in each pixel. If None is given,then the
  9. median value of that band from across the images is used for that pixel
  10. value. If None is specified as a reducer,the corresponding band(s) will
  11. be dropped. Combining None reducer(s) with a normalized sum effectively
  12. subtracts an endmember under the unity constraint. Arguments:
  13. reducers One of (''min'',''max'',''mean'',''median'',None) for each endmember
  14. rasters One or more raster files to composite
  15. normalize True (by default) to normalize results by their sum
  16. nodata The NoData value (defaults to -9999)
  17. dtype The data type to coerce in the output array; very important if the desired output is float but NoData value is integer
  18. ''''''
  19. shp = rasters[0].shape
  20. num_non_null_bands = shp[0] - len([b for b in reducers if b is None])
  21. assert all(map(lambda x: x == shp, [r.shape for r in rasters])), ''Rasters must have the same shape''
  22. assert len(reducers) == shp[0], ''Must provide a reducer for each band (including None to drop the band)''
  23.  
  24. # Swap the sequence of rasters for a sequence of bands,then collapse the X-Y axes
  25. stack = np.array(rasters).swapaxes(0, 1).reshape(shp[0], len(rasters), shp[-1]*shp[-2])
  26.  
  27. # Mask out NoData values
  28. stack_masked = np.ma.masked_where(stack == nodata, stack)
  29.  
  30. # For each band (or endmember)...
  31. band_arrays = []
  32. for i in range(shp[0]):
  33. if reducers[i] in (''min'', ''max'', ''median'', ''mean''):
  34. band_arrays.append(getattr(np.ma, reducers[i])(stack_masked[i, ...], axis=0))
  35.  
  36. # Stack each reduced band (and reshape to multi-band image)
  37. final_stack = np.ma.vstack(band_arrays).reshape((num_non_null_bands, shp[-2], shp[-1]))
  38.  
  39. # Calculate a normalized sum (e.g.,fractions must sum to one)
  40. if normalize is not None:
  41. constant = getattr(final_stack, normalize)(axis=0) # The sum across the bands
  42. constant.set_fill_value(1.0) # NaNs will be divided by 1.0
  43. constant = np.ma.repeat(constant, num_non_null_bands, axis=0).reshape(final_stack.shape)
  44. # Divide the values in each band by the normalized sum across the bands
  45. if num_non_null_bands > 1:
  46. final_stack = final_stack / constant.swapaxes(0, 1)
  47.  
  48. else:
  49. final_stack = final_stack / constant
  50.  
  51. # NOTE: Essential to cast type,e.g.,to float in case first pixel (i.e. top-left) is all NoData of an integer type
  52. final_stack.set_fill_value(dtype(nodata)) # Fill NoData for NaNs
  53.  
  54. return final_stack.filled()

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel(a, order=''C'')

  Return a flattened array

numpy.chararray.flatten(order=''C'')

  Return a copy of the array collapsed into one dimension

numpy.squeeze(a, axis=None)

  Remove single-dimensional entries from the shape of an array.

 

相同点: 将多维数组 降为 一维数组

不同点:

  ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;

  flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;

  squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;

 

ravel()示例:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 
20 print(a)
21 log_type(''a'',a)

 

flatten()示例

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

squeeze()示例:

1. 没有single-dimensional entries的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。

 

2. 有single-dimentional entries 的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10 
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

一、Numpy数组创建

 part 1:np.linspace(起始值,终止值,元素总个数

 

import numpy as np
''''''
numpy中的ndarray数组
''''''

ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)

''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)

# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)

print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)

# 创建二维数组:
print(np.zeros ((3,4)))

print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)

# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim)  # 返回:3(维)

 

结果图:

 

part 2 :np.linspace ( 起始值,终止值,元素总个数)

 

import numpy as np
a = np.arange( 10, 30, 5 )

b = np.arange( 0, 2, 0.3 )

c = np.arange(12).reshape(4,3)

d = np.random.random((2,3))  # 取-1到1之间的随机数,要求设置为诶2行3列的结构

print(a)
print(b)
print(c)
print(d)

print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))

print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))

 

结果图:

 

 

 

 

二、Numpy的ndarray对象属性:

数组的结构:array.shape

数组的维度:array.ndim

元素的类型:array.dtype

数组元素的个数:array.size

数组的索引(下标):array[0]

 

''''''
数组的基本属性
''''''
import numpy as np

print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)     # 打印数组结构
print(len(a))      # 打印有多少行
print(a.ndim)     # 打印维度
print(a.dtype)    # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size)    # 打印数组的总元素个数


print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)

# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, )  # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)

# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3)   # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )

print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])

print("-----------------")


# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
    for j in range(ary.shape[1]):
        for k in range(ary.shape[2]):
            print(ary[i, j, k], end='' '')
            

 

结果图:

 

今天的关于Python numpy 模块-ma() 实例源码python中numpy模块的分享已经结束,谢谢您的关注,如果想了解更多关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的相关知识,请在本站进行查询。

本文标签: