GVKun编程网logo

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

3

这篇文章主要围绕Pythonnumpy模块-iscomplex()实例源码和python中numpy模块展开,旨在为您提供一份详细的参考资料。我们将全面介绍Pythonnumpy模块-iscomple

这篇文章主要围绕Python numpy 模块-iscomplex() 实例源码python中numpy模块展开,旨在为您提供一份详细的参考资料。我们将全面介绍Python numpy 模块-iscomplex() 实例源码的优缺点,解答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 模块-iscomplex() 实例源码(python中numpy模块)

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

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

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

项目:pyRSSs    作者:butala    | 项目源码 | 文件源码
  1. def spectrum(x,
  2. n0=0,
  3. T_s=1,
  4. oversample=1,
  5. only_positive=True):
  6. """
  7. Return the spectrum for the signal *x* calculated via FFT and the
  8. associated frequencies as a tuple. The *n0* parameter gives the
  9. index in *x* for time index 0 (*n0* = 0 means that `x[0]` is at
  10. time 0). The number of spectral samples returned is the next power
  11. of 2 greater than the length of *x* multiplied by *oversample*. If
  12. *only_positive*,return the spectrum only for positive frequencies
  13. (and raise an exception if *x* is not real).
  14. """
  15. assert oversample >= 1 and isinstance(oversample, int)
  16. N = nextpow2(len(x)) * 2**(oversample - 1)
  17. X = NP.fft.fft(x, n=N) * T_s
  18. f = NP.fft.fftfreq(N, d=T_s)
  19. if n0 != 0:
  20. X *= NP.exp(-1j * 2 * math.pi * NP.arange(N) * n0 / N)
  21. X = NP.fft.fftshift(X)
  22. f = NP.fft.fftshift(f)
  23. if only_positive:
  24. if any(NP.iscomplex(x)):
  25. raise ValueError(''x is complex and only returning information for positive frequencies --- this is likely not what you want to do'')
  26. X = X[f >= 0]
  27. f = f[f >= 0]
  28. return X, f
项目:pisap    作者:neurospin    | 项目源码 | 文件源码
  1. def plot_data(data, scroll_axis=2):
  2. """ Plot an image associated data.
  3. Currently support on 1D,2D or 3D data.
  4.  
  5. Parameters
  6. ----------
  7. data: array
  8. the data to be displayed.
  9. scroll_axis: int (optional,default 2)
  10. the scroll axis for 3d data.
  11. """
  12. # Check input parameters
  13. if data.ndim not in range(1, 4):
  14. raise ValueError("Unsupported data dimension.")
  15.  
  16. # Deal with complex data
  17. if numpy.iscomplex(data).any():
  18. data = numpy.abs(data)
  19.  
  20. # Create application
  21. app = pyqtgraph.mkQApp()
  22.  
  23. # Create the widget
  24. if data.ndim == 3:
  25. indices = [i for i in range(3) if i != scroll_axis]
  26. indices = [scroll_axis] + indices
  27. widget = pyqtgraph.image(numpy.transpose(data, indices))
  28. elif data.ndim == 2:
  29. widget = pyqtgraph.image(data)
  30. else:
  31. widget = pyqtgraph.plot(data)
  32.  
  33. # Run application
  34. app.exec_()
项目:CSB    作者:csb-toolBox    | 项目源码 | 文件源码
  1. def average_structure(X):
  2. """
  3. Calculate an average structure from an ensemble of structures
  4. (i.e. X is a rank-3 tensor: X[i] is a (N,3) configuration matrix).
  5.  
  6. @param X: m x n x 3 input vector
  7. @type X: numpy array
  8.  
  9. @return: average structure
  10. @rtype: (n,3) numpy.array
  11. """
  12. from numpy.linalg import eigh
  13.  
  14. B = csb.numeric.gower_matrix(X)
  15. v, U = eigh(B)
  16. if numpy.iscomplex(v).any():
  17. v = v.real
  18. if numpy.iscomplex(U).any():
  19. U = U.real
  20.  
  21. indices = numpy.argsort(v)[-3:]
  22. v = numpy.take(v, indices, 0)
  23. U = numpy.take(U, 1)
  24.  
  25. x = U * numpy.sqrt(v)
  26. i = 0
  27. while is_mirror_image(x, X[0]) and i < 2:
  28. x[:, i] *= -1
  29. i += 1
  30. return x
项目:HJW_KL_divergence_estimator    作者:Mathegineer    | 项目源码 | 文件源码
  1. def rel_entropy_true(p, q):
  2. """KL divergence (relative entropy) D(p||q) in bits
  3.  
  4. Returns a scalar entropy when the input distributions p and q are
  5. vectors of probability masses,or returns in a row vector the
  6. columnwise relative entropies of the input probability matrices p and
  7. q"""
  8.  
  9. if type(p) == list or type(q) == tuple:
  10. p = np.array(p)
  11. if type(q) == list or type(q) == tuple:
  12. q = np.array(q)
  13.  
  14. if not p.shape == q.shape:
  15. raise Exception(''p and q must be equal sizes'',
  16. ''p: '' + str(p.shape),
  17. ''q: '' + str(q.shape))
  18.  
  19. if (np.iscomplex(p).any() or not
  20. np.isfinite(p).any() or
  21. (p < 0).any() or
  22. (p > 1).any()):
  23. raise Exception(''The probability elements of p must be real numbers''
  24. ''between 0 and 1.'')
  25.  
  26. if (np.iscomplex(q).any() or not
  27. np.isfinite(q).any() or
  28. (q < 0).any() or
  29. (q > 1).any()):
  30. raise Exception(''The probability elements of q must be real numbers''
  31. ''between 0 and 1.'')
  32.  
  33. eps = math.sqrt(np.spacing(1))
  34. if (np.abs(np.sum(p, axis=0) - 1) > eps).any():
  35. raise Exception(''Sum of the probability elements of p must equal 1.'')
  36. if (np.abs(np.sum(q, axis=0) - 1) > eps).any():
  37. raise Exception(''Sum of the probability elements of q must equal 1.'')
  38.  
  39. return sum(np.log2((p**p) / (q**p)))
项目:mathpy    作者:aschleg    | 项目源码 | 文件源码
  1. def pnorm(self, p):
  2. r"""
  3. Calculates the p-norm of a vector.
  4.  
  5. Parameters
  6. ----------
  7. p : int
  8. Used in computing the p-norm. This should only be set
  9. when calculating the pnorm of a vector is desired.
  10.  
  11. Returns
  12. -------
  13. pn : float
  14. The p-norm of the vector.
  15.  
  16. Notes
  17. -----
  18. The p-norm,which is considered a class of vector norms is defined as:
  19.  
  20. .. math::
  21.  
  22. ||x||_p = \\sqrt[p]{|x_1|^p + |x_2|^p + \\cdots + |x_n|^p} \\qquad p \\geq 1
  23.  
  24. References
  25. ----------
  26. Golub,G.,& Van Loan,C. (2013). Matrix computations (3rd ed.). Baltimore (MD): Johns Hopkins U.P.
  27.  
  28. """
  29. if p != np.floor(p):
  30. p = np.floor(p)
  31.  
  32. if np.iscomplex(p) or p < 1:
  33. raise ValueError(''p must be at least 1 and real'')
  34.  
  35. pn = np.sum(np.absolute(self.x) ** p) ** (1. / p)
  36.  
  37. return pn
项目:SpicePy    作者:giaccone    | 项目源码 | 文件源码
  1. def __str__(self):
  2. # create local dictionary to convert node-numbers to node-labels
  3. num2node_label = {num: name for name, num in self.node_label2num.items()}
  4.  
  5. # build message to print
  6. msg = ''------------------------\\n''
  7. msg += '' SpicePy.Network:\\n''
  8. msg += ''------------------------\\n''
  9. for ele, nodes, val in zip(self.names, self.nodes, self.values):
  10. # if val is a list --> ele is a transient source
  11. if isinstance(val, list):
  12. if self.source_type[ele] == ''pwl'':
  13. fmt = "{} {} {} {}(" + "{} " * (len(val[0]) - 1) + "{})\\n"
  14. msg += fmt.format(ele, num2node_label[nodes[0]], num2node_label[nodes[1]], self.source_type[ele], *val[0])
  15. else:
  16. fmt = "{} {} {} {}(" + "{} " * (len(val) - 1) + "{})\\n"
  17. msg += fmt.format(ele, *val)
  18. # if val is complex --> ele is a phasor
  19. elif np.iscomplex(val):
  20. msg += "{} {} {} {} {}\\n".format(ele, np.abs(val), np.angle(val) * 180/np.pi)
  21. # if ele is C or L
  22. elif ele[0].upper() == ''C'' or ele[0].upper() == ''L'':
  23. # check if an i.c. is present and print it
  24. if ele in self.IC:
  25. msg += "{} {} {} {} ic={}\\n".format(ele, val, self.IC[ele])
  26. # otherwise...
  27. else:
  28. msg += "{} {} {} {}\\n".format(ele, val)
  29. # otherwise...general case --> ele n+ n- val
  30. else:
  31. msg += "{} {} {} {}\\n".format(ele, val)
  32.  
  33. # add analysis
  34. msg += " ".join(self.analysis) + ''\\n''
  35.  
  36. # if a plot command is present,add it
  37. if self.plot_cmd is not None:
  38. msg += self.plot_cmd + ''\\n''
  39.  
  40. # add number of nodes (reference node is included) and number of branches
  41. msg += ''------------------------\\n''
  42. msg += ''* number of nodes {}\\n''.format(self.node_num + 1)
  43. msg += ''* number of branches {}\\n''.format(len(self.names))
  44. msg += ''------------------------\\n''
  45.  
  46. return msg
项目:meshpy    作者:BerkeleyAutomation    | 项目源码 | 文件源码
  1. def find_zero_crossing_quadratic(x1, y1, x2, y2, x3, y3, eps = 1.0):
  2. """ Find zero crossing using quadratic approximation along 1d line"""
  3. # compute coords along 1d line
  4. v = x2 - x1
  5. v = v / np.linalg.norm(v)
  6. if v[v!=0].shape[0] == 0:
  7. logging.error(''Difference is 0. Probably a bug'')
  8.  
  9. t1 = 0
  10. t2 = (x2 - x1)[v!=0] / v[v!=0]
  11. t2 = t2[0]
  12. t3 = (x3 - x1)[v!=0] / v[v!=0]
  13. t3 = t3[0]
  14.  
  15. # solve for quad approx
  16. x1_row = np.array([t1**2, t1, 1])
  17. x2_row = np.array([t2**2, t2, 1])
  18. x3_row = np.array([t3**2, t3, 1])
  19. X = np.array([x1_row, x2_row, x3_row])
  20. y_vec = np.array([y1, y3])
  21. try:
  22. w = np.linalg.solve(X, y_vec)
  23. except np.linalg.LinAlgError:
  24. logging.error(''Singular matrix. Probably a bug'')
  25. return None
  26.  
  27. # get positive roots
  28. possible_t = np.roots(w)
  29. t_zc = None
  30. for i in range(possible_t.shape[0]):
  31. if possible_t[i] >= 0 and possible_t[i] <= 10 and not np.iscomplex(possible_t[i]):
  32. t_zc = possible_t[i]
  33.  
  34. # if no positive roots find min
  35. if np.abs(w[0]) < 1e-10:
  36. return None
  37.  
  38. if t_zc is None:
  39. t_zc = -w[1] / (2 * w[0])
  40.  
  41. if t_zc < -eps or t_zc > eps:
  42. return None
  43.  
  44. x_zc = x1 + t_zc * v
  45. return x_zc
项目:MinimaxFilter    作者:jihunhamm    | 项目源码 | 文件源码
  1. def run(X,y1,y2,dmax=None):
  2.  
  3. D,N = X.shape
  4. y1_unique,J1 = np.unique(y1, return_inverse=True)
  5. ny1 = y1_unique.size
  6.  
  7. y2_unique,J2 = np.unique(y2, return_inverse=True)
  8. ny2 = y2_unique.size
  9.  
  10. Y1 = np.zeros((ny1,N))
  11. Y2 = np.zeros((ny2,N))
  12. Y1[J1,range(N)] = 1.
  13. Y2[J2,range(N)] = 1.
  14.  
  15. XY2 = np.dot(X,Y2.T) # D x ny2
  16. XY2Y2X = np.dot(XY2,XY2.T) # D x D
  17. XX = np.dot(X,X.T) # D x D
  18.  
  19. P = np.zeros((D,0))
  20. Sj = np.dot(X,Y1.T) # D x ny1
  21.  
  22. if dmax==None:
  23. dmax = D
  24.  
  25. for d in range(dmax):
  26. if d>0:
  27. invPP = np.linalg.pinv(np.dot(P.T,P))
  28. Sj -= np.dot(np.dot(np.dot(P,invPP),P.T),Sj)
  29.  
  30. C = np.dot(Sj,Sj.T) - XY2Y2X
  31. C = 0.5*(C+C.T)
  32. dd,E = scipy.linalg.eigh(C,eigvals=(D-1,D-1)) # ascending order
  33.  
  34. assert np.isnan(dd).any()==False
  35. assert np.iscomplex(dd).any()==False
  36. #dd = dd[::-1] #
  37. #E = E[:,::-1]
  38. wj = E#E[:,0] # D x 1
  39. pj = np.dot(XX,wj) / np.dot(np.dot(wj.T,XX),wj) # D x 1
  40. P = np.hstack((P,pj.reshape((D,1)))) # D x d
  41.  
  42.  
  43. #P = P/np.tile(np.sqrt((P**2).sum(axis=0,keepdims=True)),(D,1))
  44. #% They need not be orthogonal.
  45. return P
项目:MinimaxFilter    作者:jihunhamm    | 项目源码 | 文件源码
  1. def run(X,y2):
  2. # function [E,dd] = privacyLDA(X,y1,y2)
  3. # %max_W0 tr(W0''*C1*W0) - tr(W0''*C2*W0)
  4. D,N = X.shape
  5. y1_unique = np.unique(y1)
  6. #print y1_unique
  7. #[y1_unique,~,J1] = unique(y1);
  8. #ny1 = y1_unique.size
  9.  
  10. y2_unique = np.unique(y2)
  11. #print y2_unique
  12. #[y2_unique,J2] = unique(y2);
  13. #ny2 = y2_unique.size
  14.  
  15. C1 = np.zeros((D,D))
  16. C2 = np.zeros((D,D))
  17. mu = X.mean(axis=1).reshape((D,1))
  18. #print mu.shape
  19.  
  20. for k in np.nditer(y1_unique):
  21. indk = np.where(y1==k)[0]
  22. muk = X[:,indk].mean(axis=1).reshape((D,1))
  23. #muk -= np.kron(np.ones((1,len(indk))),mu)
  24. #%C1 = C1 + ny1*(muk-mu)*(muk-mu)'';
  25. C1 = C1 + len(indk)*np.dot(muk-mu,(muk-mu).T)
  26.  
  27. for k in np.nditer(y2_unique):
  28. indk = np.where(y2==k)[0]
  29. muk = X[:,mu)
  30. #%C1 = C1 + ny1*(muk-mu)*(muk-mu)'';
  31. C2 = C2 + len(indk)*np.dot(muk-mu,(muk-mu).T)
  32.  
  33. C1 = C1 + 1e-8*np.trace(C1)*np.eye(D)#
  34. C2 = C2 + 1e-8*np.trace(C2)*np.eye(D)#
  35. C1 = 0.5*(C1+C1.T)#;% + 1E-8*trace(C1)*eye(D);
  36. C2 = 0.5*(C2+C2.T)#;% + 1E-8*trace(C2)*eye(D);
  37.  
  38.  
  39. dd,E = scipy.linalg.eigh(C1,C2) # ascending order
  40.  
  41. #print dd.shape
  42. #print E.shape
  43.  
  44. assert np.isnan(dd).any()==False
  45. assert np.iscomplex(dd).any()==False
  46. #[dd,ind] = sort(diag(dd),''descend'');
  47. #print dd
  48. dd = dd[::-1] #
  49. E = E[:,::-1]
  50.  
  51. E = E/np.tile(np.sqrt((E**2).sum(axis=0,keepdims=True)),(D,1))
  52. #% They need not be orthogonal.
  53.  
  54. #print dd.shape
  55. #print E.shape
  56.  
  57. return (E,dd)
项目:piradar    作者:scivision    | 项目源码 | 文件源码
  1. def cwplot(fb_est,rx,t,fs:int,fn) -> None:
  2. #%% time
  3. fg,axs = subplots(1,2,figsize=(12,6))
  4. ax = axs[0]
  5. ax.plot(t, rx.T.real)
  6. ax.set_xlabel(''time [sec]'')
  7. ax.set_ylabel(''amplitude'')
  8. ax.set_title(''Noisy,jammed receive signal'')
  9. #%% periodogram
  10. if DTPG >= (t[-1]-t[0]):
  11. dt = (t[-1]-t[0])/4
  12. else:
  13. dt = DTPG
  14.  
  15. dtw = 2*dt # seconds to window
  16. tstep = ceil(dt*fs)
  17. wind = ceil(dtw*fs);
  18. nfft = zeropadfactor*wind
  19.  
  20. f,Sraw = signal.welch(rx.ravel(), fs,
  21. nperseg=wind,noverlap=tstep,nfft=nfft,
  22. return_onesided=False)
  23.  
  24. if np.iscomplex(rx).any():
  25. f = np.fft.fftshift(f); Sraw = np.fft.fftshift(Sraw)
  26.  
  27. ax=axs[1]
  28. ax.plot(f,Sraw,''r'',label=''raw signal'')
  29.  
  30. fc_est = f[Sraw.argmax()]
  31.  
  32. #ax.set_yscale(''log'')
  33. ax.set_xlim([fc_est-200,fc_est+200])
  34. ax.set_xlabel(''frequency [Hz]'')
  35. ax.set_ylabel(''amplitude'')
  36. ax.legend()
  37.  
  38. esttxt=''''
  39.  
  40. if fn is None: # simulation
  41. ax.axvline(ft+fb0,color=''red'',linestyle=''--'',label=''true freq.'')
  42. esttxt += f''true: {ft+fb0} Hz ''
  43.  
  44. for e in fb_est:
  45. ax.axvline(e,color=''blue'',label=''est. freq.'')
  46.  
  47. esttxt += '' est: '' + str(fb_est) +'' Hz''
  48.  
  49. ax.set_title(esttxt)
项目:piradar    作者:scivision    | 项目源码 | 文件源码
  1. def cw_est(rx, fs:int, Ntone:int, method:str=''esprit'', usepython=False, useall=False):
  2. """
  3. estimate beat frequency using subspace frequency estimation techniques.
  4. This is much faster in Fortran,but to start using Python alone doesn''t require compiling Fortran.
  5.  
  6. ESPRIT and RootMUSIC are two popular subspace techniques.
  7.  
  8. Matlab''s rootmusic is a far inferior FFT-based method with very poor accuracy vs. my implementation.
  9. """
  10. assert isinstance(method,str)
  11. method = method.lower()
  12.  
  13. tic = time()
  14. if method == ''esprit'':
  15. #%% ESPRIT
  16. if rx.ndim == 2:
  17. assert usepython,''Fortran not yet configured for multi-pulse case''
  18. Ntone *= 2
  19.  
  20.  
  21. if usepython or (Sc is None and Sr is None):
  22. print(''Python ESPRIT'')
  23. fb_est, sigma = esprit(rx, Ntone, Nblockest, fs)
  24. elif np.iscomplex(rx).any():
  25. print(''Fortran complex64 ESPRIT'')
  26. fb_est, sigma = Sc.subspace.esprit(rx,Ntone,Nblockest,fs)
  27. else: # real signal
  28. print(''Fortran float32 ESPRIT'')
  29. fb_est, sigma = Sr.subspace.esprit(rx,fs)
  30.  
  31. fb_est = abs(fb_est)
  32. #%% ROOTMUSIC
  33. elif method == ''rootmusic'':
  34. fb_est, sigma = rootmusic(rx,fs)
  35. else:
  36. raise ValueError(f''unkNown estimation method: {method}'')
  37. print(f''computed via {method} in {time()-tic:.1f} seconds.'')
  38. #%% improvised process for CW only without notch filter
  39. # assumes first two results have largest singular values (from SVD)
  40. if not useall:
  41. i = sigma > 0.001 # arbitrary
  42. fb_est = fb_est[i]
  43. sigma = sigma[i]
  44.  
  45. # if fb_est.size>1:
  46. # ii = np.argpartition(sigma,Ntone-1)[:Ntone-1]
  47. # fb_est = fb_est[ii]
  48. # sigma = sigma[ii]
  49.  
  50.  
  51. return fb_est, sigma

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 模块-iscomplex() 实例源码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 ()、数组基本属性等相关知识的信息别忘了在本站进行查找喔。

本文标签: