GVKun编程网logo

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

4

此处将为大家介绍关于Pythonnumpy模块-poly()实例源码的详细内容,并且为您解答有关python中numpy模块的相关问题,此外,我们还将为您介绍关于Jupyter中的Numpy在打印时出

此处将为大家介绍关于Python numpy 模块-poly() 实例源码的详细内容,并且为您解答有关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 模块-poly() 实例源码(python中numpy模块)

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

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

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

项目:oasis    作者:j-friedrich    | 项目源码 | 文件源码
  1. def estimate_time_constant(y, p=2, sn=None, lags=5, fudge_factor=1.):
  2. """
  3. Estimate AR model parameters through the autocovariance function
  4.  
  5. Parameters
  6. ----------
  7. y : array,shape (T,)
  8. One dimensional array containing the fluorescence intensities with
  9. one entry per time-bin.
  10. p : positive integer
  11. order of AR system
  12. sn : float
  13. sn standard deviation,estimated if not provided.
  14. lags : positive integer
  15. number of additional lags where he autocovariance is computed
  16. fudge_factor : float (0< fudge_factor <= 1)
  17. shrinkage factor to reduce bias
  18.  
  19. Returns
  20. -------
  21. g : estimated coefficients of the AR process
  22. """
  23.  
  24. if sn is None:
  25. sn = GetSn(y)
  26.  
  27. lags += p
  28. xc = axcov(y, lags)
  29. xc = xc[:, np.newaxis]
  30.  
  31. A = scipy.linalg.toeplitz(xc[lags + np.arange(lags)],
  32. xc[lags + np.arange(p)]) - sn**2 * np.eye(lags, p)
  33. g = np.linalg.lstsq(A, xc[lags + 1:])[0]
  34. gr = np.roots(np.concatenate([np.array([1]), -g.flatten()]))
  35. gr = (gr + gr.conjugate()) / 2.
  36. gr[gr > 1] = 0.95 + np.random.normal(0, 0.01, np.sum(gr > 1))
  37. gr[gr < 0] = 0.15 + np.random.normal(0, np.sum(gr < 0))
  38. g = np.poly(fudge_factor * gr)
  39. g = -g[1:]
  40.  
  41. return g.flatten()
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_poly(self):
  2. assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
  3. [1, -3, -2, 6])
  4.  
  5. # From matlab docs
  6. A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
  7. assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])
  8.  
  9. # Should produce real output for perfect conjugates
  10. assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
  11. assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
  12. 1-2j, 1.+3.5j, 1-3.5j])))
  13. assert_(np.isrealobj(np.poly([1j, -1j, 1-2j, 1+3j, 1-3.j])))
  14. assert_(np.isrealobj(np.poly([1j, 1-2j])))
  15. assert_(np.isrealobj(np.poly([1j, 2j, -2j])))
  16. assert_(np.isrealobj(np.poly([1j, -1j])))
  17. assert_(np.isrealobj(np.poly([1, -1])))
  18.  
  19. assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))
  20.  
  21. np.random.seed(42)
  22. a = np.random.randn(100) + 1j*np.random.randn(100)
  23. assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_objects(self):
  2. from decimal import Decimal
  3. p = np.poly1d([Decimal(''4.0''), Decimal(''3.0''), Decimal(''2.0'')])
  4. p2 = p * Decimal(''1.333333333333333'')
  5. assert_(p2[1] == Decimal("3.9999999999999990"))
  6. p2 = p.deriv()
  7. assert_(p2[1] == Decimal(''8.0''))
  8. p2 = p.integ()
  9. assert_(p2[3] == Decimal("1.333333333333333333333333333"))
  10. assert_(p2[2] == Decimal(''1.5''))
  11. assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
  12. p = np.poly([Decimal(1), Decimal(2)])
  13. assert_equal(np.poly([Decimal(1), Decimal(2)]),
  14. [1, Decimal(-3), Decimal(2)])
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_zero_dims(self):
  2. try:
  3. np.poly(np.zeros((0, 0)))
  4. except ValueError:
  5. pass
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_poly_int_overflow(self):
  2. """
  3. Regression test for gh-5096.
  4. """
  5. v = np.arange(1, 21)
  6. assert_almost_equal(np.poly(v), np.poly(np.diag(v)))
项目:tools    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), order + 1))
  6. for i in range(len(all_lsf)):
  7. lsf = all_lsf[i]
  8. zeros = np.exp(1j * lsf)
  9. sum_zeros = zeros[::2]
  10. diff_zeros = zeros[1::2]
  11. sum_zeros = np.hstack((sum_zeros, np.conj(sum_zeros)))
  12. diff_zeros = np.hstack((diff_zeros, np.conj(diff_zeros)))
  13. sum_filt = np.poly(sum_zeros)
  14. diff_filt = np.poly(diff_zeros)
  15.  
  16. if order % 2 != 0:
  17. deconv_diff = sg.convolve(diff_filt, 0, -1])
  18. deconv_sum = sum_filt
  19. else:
  20. deconv_diff = sg.convolve(diff_filt, -1])
  21. deconv_sum = sg.convolve(sum_filt, 1])
  22.  
  23. lpc = .5 * (deconv_sum + deconv_diff)
  24. # Last coefficient is 0 and not returned
  25. all_lpc[i] = lpc[:-1]
  26. return np.squeeze(all_lpc)
项目:tools    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_objects(self):
  2. from decimal import Decimal
  3. p = np.poly1d([Decimal(''4.0''), Decimal(2)])
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_zero_dims(self):
  2. try:
  3. np.poly(np.zeros((0, 0)))
  4. except ValueError:
  5. pass
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_poly_int_overflow(self):
  2. """
  3. Regression test for gh-5096.
  4. """
  5. v = np.arange(1, np.poly(np.diag(v)))
项目:SCaIP    作者:simonsfoundation    | 项目源码 | 文件源码
  1. def estimate_time_constant(fluor, p = 2, sn = None, lags = 5, fudge_factor = 1.):
  2. """
  3. Estimate AR model parameters through the autocovariance function
  4. Inputs
  5. ----------
  6. fluor : nparray
  7. One dimensional array containing the fluorescence intensities with
  8. one entry per time-bin.
  9. p : positive integer
  10. order of AR system
  11. sn : float
  12. noise standard deviation,estimated if not provided.
  13. lags : positive integer
  14. number of additional lags where he autocovariance is computed
  15. fudge_factor : float (0< fudge_factor <= 1)
  16. shrinkage factor to reduce bias
  17.  
  18. Return
  19. -----------
  20. g : estimated coefficients of the AR process
  21. """
  22.  
  23.  
  24. if sn is None:
  25. sn = GetSn(fluor)
  26.  
  27. lags += p
  28. xc = axcov(fluor,lags)
  29. xc = xc[:,np.newaxis]
  30.  
  31. A = scipy.linalg.toeplitz(xc[lags+np.arange(lags)],xc[lags+np.arange(p)]) - sn**2*np.eye(lags,p)
  32. g = np.linalg.lstsq(A,xc[lags+1:])[0]
  33. gr = np.roots(np.concatenate([np.array([1]),-g.flatten()]))
  34. gr = (gr+gr.conjugate())/2.
  35. gr[gr>1] = 0.95 + np.random.normal(0,0.01,np.sum(gr>1))
  36. gr[gr<0] = 0.15 + np.random.normal(0,np.sum(gr<0))
  37. g = np.poly(fudge_factor*gr)
  38. g = -g[1:]
  39.  
  40. return g.flatten()
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_objects(self):
  2. from decimal import Decimal
  3. p = np.poly1d([Decimal(''4.0''), Decimal(2)])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_zero_dims(self):
  2. try:
  3. np.poly(np.zeros((0, 0)))
  4. except ValueError:
  5. pass
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_poly_int_overflow(self):
  2. """
  3. Regression test for gh-5096.
  4. """
  5. v = np.arange(1, np.poly(np.diag(v)))
项目:apicultor    作者:sonidosmutantes    | 项目源码 | 文件源码
  1. def z_coeff(Poles,Zeros,fs,g,fg,fo = ''none''):
  2. if fg == np.inf:
  3. fg = fs/2
  4. if fo == ''none'':
  5. beta = 1.0
  6. else:
  7. beta = f_warp(fo,fs)/fo
  8. a = np.poly(z_from_f(beta*np.array(Poles),fs))
  9. b = np.poly(z_from_f(beta*np.array(Zeros),fs))
  10. gain = 10.**(g/20.)/abs(Fz_at_f(beta*np.array(Poles),beta*np.array(Zeros),fs))
  11.  
  12. return (a,b*gain)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_objects(self):
  2. from decimal import Decimal
  3. p = np.poly1d([Decimal(''4.0''), Decimal(2)])
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_zero_dims(self):
  2. try:
  3. np.poly(np.zeros((0, 0)))
  4. except ValueError:
  5. pass
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_poly_int_overflow(self):
  2. """
  3. Regression test for gh-5096.
  4. """
  5. v = np.arange(1, np.poly(np.diag(v)))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_objects(self):
  2. from decimal import Decimal
  3. p = np.poly1d([Decimal(''4.0''), Decimal(2)])
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_zero_dims(self):
  2. try:
  3. np.poly(np.zeros((0, 0)))
  4. except ValueError:
  5. pass
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_poly_int_overflow(self):
  2. """
  3. Regression test for gh-5096.
  4. """
  5. v = np.arange(1, np.poly(np.diag(v)))
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:crikey    作者:kastnerkyle    | 项目源码 | 文件源码
  1. def lsf_to_lpc(all_lsf):
  2. if len(all_lsf.shape) < 2:
  3. all_lsf = all_lsf[None]
  4. order = all_lsf.shape[1]
  5. all_lpc = np.zeros((len(all_lsf), 1])
  6.  
  7. lpc = .5 * (deconv_sum + deconv_diff)
  8. # Last coefficient is 0 and not returned
  9. all_lpc[i] = lpc[:-1]
  10. return np.squeeze(all_lpc)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_objects(self):
  2. from decimal import Decimal
  3. p = np.poly1d([Decimal(''4.0''), Decimal(2)])
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_zero_dims(self):
  2. try:
  3. np.poly(np.zeros((0, 0)))
  4. except ValueError:
  5. pass
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_poly_int_overflow(self):
  2. """
  3. Regression test for gh-5096.
  4. """
  5. v = np.arange(1, np.poly(np.diag(v)))

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 模块-poly() 实例源码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 ()、数组基本属性等更多相关知识的信息可以在本站进行查询。

本文标签: