GVKun编程网logo

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

2

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

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

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

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

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

项目:pyRSSs    作者:butala    | 项目源码 | 文件源码
  1. def operate(self, x):
  2. """
  3. Apply the separable filter to the signal vector *x*.
  4. """
  5. X = NP.fft.fftn(x, s=self.k_full)
  6. if NP.isrealobj(self.h) and NP.isrealobj(x):
  7. y = NP.real(NP.fft.ifftn(self.H * X))
  8. else:
  9. y = NP.fft.ifftn(self.H * X)
  10.  
  11. if self.mode == ''full'' or self.mode == ''circ'':
  12. return y
  13. elif self.mode == ''valid'':
  14. slice_list = []
  15. for i in range(self.ndim):
  16. if self.m[i]-1 == 0:
  17. slice_list.append(slice(None, None, None))
  18. else:
  19. slice_list.append(slice(self.m[i]-1, -(self.m[i]-1), None))
  20. return y[slice_list]
  21. else:
  22. assert(False)
项目:arlpy    作者:org-arl    | 项目源码 | 文件源码
  1. def correlate_periodic(a, v=None):
  2. """Cross-correlation of two 1-dimensional periodic sequences.
  3.  
  4. a and v must be sequences with the same length. If v is not specified,it is
  5. assumed to be the same as a (i.e. the function computes auto-correlation).
  6.  
  7. :param a: input sequence #1
  8. :param v: input sequence #2
  9. :returns: discrete periodic cross-correlation of a and v
  10. """
  11. a_fft = _np.fft.fft(_np.asarray(a))
  12. if v is None:
  13. v_cfft = a_fft.conj()
  14. else:
  15. v_cfft = _np.fft.fft(_np.asarray(v)).conj()
  16. x = _np.fft.ifft(a_fft * v_cfft)
  17. if _np.isrealobj(a) and (v is None or _np.isrealobj(v)):
  18. x = x.real
  19. return x
项目:pumpp    作者:bmcfee    | 项目源码 | 文件源码
  1. def inverse(self, encoded, duration=None):
  2. ''''''Inverse static tag transformation''''''
  3.  
  4. ann = jams.Annotation(namespace=self.namespace, duration=duration)
  5.  
  6. if np.isrealobj(encoded):
  7. detected = (encoded >= 0.5)
  8. else:
  9. detected = encoded
  10.  
  11. for vd in self.encoder.inverse_transform(np.atleast_2d(detected))[0]:
  12. vid = np.flatnonzero(self.encoder.transform(np.atleast_2d(vd)))
  13. ann.append(time=0,
  14. duration=duration,
  15. value=vd,
  16. confidence=encoded[vid])
  17. return ann
项目:pumpp    作者:bmcfee    | 项目源码 | 文件源码
  1. def decode_events(self, encoded):
  2. ''''''Decode labeled events into (time,value) pairs
  3.  
  4. Parameters
  5. ----------
  6. encoded : np.ndarray,shape=(n_frames,m)
  7. Frame-level annotation encodings as produced by ``encode_events``.
  8.  
  9. Real-valued inputs are thresholded at 0.5.
  10.  
  11. Returns
  12. -------
  13. [(time,value)] : iterable of tuples
  14. where `time` is the event time and `value` is an
  15. np.ndarray,shape=(m,) of the encoded value at that time
  16. ''''''
  17. if np.isrealobj(encoded):
  18. encoded = (encoded >= 0.5)
  19. times = frames_to_time(np.arange(encoded.shape[0]),
  20. sr=self.sr,
  21. hop_length=self.hop_length)
  22.  
  23. return zip(times, encoded)
项目:DeepFormants    作者:MLSpeech    | 项目源码 | 文件源码
  1. def atal(x, order, num_coefs):
  2. x = np.atleast_1d(x)
  3. n = x.size
  4. if x.ndim > 1:
  5. raise ValueError("Only rank 1 input supported for Now.")
  6. if not np.isrealobj(x):
  7. raise ValueError("Only real input supported for Now.")
  8. a, e, kk = lpc(x, order)
  9. c = np.zeros(num_coefs)
  10. c[0] = a[0]
  11. for m in range(1, order+1):
  12. c[m] = - a[m]
  13. for k in range(1, m):
  14. c[m] += (float(k)/float(m)-1)*a[k]*c[m-k]
  15. for m in range(order+1, num_coefs):
  16. for k in range(1, order+1):
  17. c[m] += (float(k)/float(m)-1)*a[k]*c[m-k]
  18. return c
项目: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))))))
项目:fluids    作者:CalebBell    | 项目源码 | 文件源码
  1. def polyval(self, chebcoeff):
  2. """
  3. Compute the interpolation values at Chebyshev points.
  4. chebcoeff: Chebyshev coefficients
  5. """
  6. N = len(chebcoeff)
  7. if N == 1:
  8. return chebcoeff
  9.  
  10. data = even_data(chebcoeff)/2
  11. data[0] *= 2
  12. data[N-1] *= 2
  13.  
  14. fftdata = 2*(N-1)*fftpack.ifft(data, axis=0)
  15. complex_values = fftdata[:N]
  16. # convert to real if input was real
  17. if np.isrealobj(chebcoeff):
  18. values = np.real(complex_values)
  19. else:
  20. values = complex_values
  21. return values
项目:fluids    作者:CalebBell    | 项目源码 | 文件源码
  1. def dct(data):
  2. """
  3. Compute DCT using FFT
  4. """
  5. N = len(data)//2
  6. fftdata = fftpack.fft(data, axis=0)[:N+1]
  7. fftdata /= N
  8. fftdata[0] /= 2.
  9. fftdata[-1] /= 2.
  10. if np.isrealobj(data):
  11. data = np.real(fftdata)
  12. else:
  13. data = fftdata
  14. return data
  15.  
  16. # ----------------------------------------------------------------
  17. # Add overloaded operators
  18. # ----------------------------------------------------------------
项目:nelpy    作者:nelpy    | 项目源码 | 文件源码
  1. def isreal(self):
  2. """Returns True if entire signal is real."""
  3. return np.all(np.isreal(self._ydata))
  4. # return np.isrealobj(self._ydata)
项目:sporco    作者:bwohlberg    | 项目源码 | 文件源码
  1. def fftconv(a, b, axes=(0,1)):
  2. """
  3. Compute a multi-dimensional convolution via the discrete Fourier Transform.
  4.  
  5. Parameters
  6. ----------
  7. a : array_like
  8. Input array
  9. b : array_like
  10. Input array
  11. axes : sequence of ints,optional (default (0,1))
  12. Axes on which to perform convolution
  13.  
  14. Returns
  15. -------
  16. ab : ndarray
  17. Convolution of input arrays,a and b,along specified axes
  18. """
  19.  
  20. if np.isrealobj(a) and np.isrealobj(b):
  21. fft = rfftn
  22. ifft = irfftn
  23. else:
  24. fft = fftn
  25. ifft = ifftn
  26. dims = np.maximum([a.shape[i] for i in axes], [b.shape[i] for i in axes])
  27. af = fft(a, dims, axes)
  28. bf = fft(b, axes)
  29. return ifft(af*bf, axes)
项目:PonyGE2    作者:PonyGE    | 项目源码 | 文件源码
  1. def evaluate(self, ind, **kwargs):
  2. """
  3. Note that math functions used in the solutions are imported from either
  4. utilities.fitness.math_functions or called from numpy.
  5.  
  6. :param ind: An individual to be evaluated.
  7. :param kwargs: An optional parameter for problems with training/test
  8. data. Specifies the distribution (i.e. training or test) upon which
  9. evaluation is to be performed.
  10. :return: The fitness of the evaluated individual.
  11. """
  12.  
  13. dist = kwargs.get(''dist'', ''training'')
  14.  
  15. if dist == "training":
  16. # Set training datasets.
  17. x = self.training_in
  18. y = self.training_exp
  19.  
  20. elif dist == "test":
  21. # Set test datasets.
  22. x = self.test_in
  23. y = self.test_exp
  24.  
  25. else:
  26. raise ValueError("UnkNown dist: " + dist)
  27.  
  28. if params[''OPTIMIZE_CONSTANTS'']:
  29. # if we are training,then optimize the constants by
  30. # gradient descent and save the resulting phenotype
  31. # string as ind.phenotype_with_c0123 (eg x[0] +
  32. # c[0] * x[1]**c[1]) and values for constants as
  33. # ind.opt_consts (eg (0.5,0.7). Later,when testing,
  34. # use the saved string and constants to evaluate.
  35. if dist == "training":
  36. return optimize_constants(x, y, ind)
  37.  
  38. else:
  39. # this string has been created during training
  40. phen = ind.phenotype_consec_consts
  41. c = ind.opt_consts
  42. # phen will refer to x (ie test_in),and possibly to c
  43. yhat = eval(phen)
  44. assert np.isrealobj(yhat)
  45.  
  46. # let''s always call the error function with the
  47. # true values first,the estimate second
  48. return params[''ERROR_METRIC''](y, yhat)
  49.  
  50. else:
  51. # phenotype won''t refer to C
  52. yhat = eval(ind.phenotype)
  53. assert np.isrealobj(yhat)
  54.  
  55. # let''s always call the error function with the true
  56. # values first,the estimate second
  57. return params[''ERROR_METRIC''](y, yhat)
项目:DeepFormants    作者:MLSpeech    | 项目源码 | 文件源码
  1. def periodogram(x, nfft=None, fs=1):
  2. """Compute the periodogram of the given signal,with the given fft size.
  3.  
  4. Parameters
  5. ----------
  6. x : array-like
  7. input signal
  8. nfft : int
  9. size of the fft to compute the periodogram. If None (default),the
  10. length of the signal is used. if nfft > n,the signal is 0 padded.
  11. fs : float
  12. Sampling rate. By default,is 1 (normalized frequency. e.g. 0.5 is the
  13. Nyquist limit).
  14.  
  15. Returns
  16. -------
  17. pxx : array-like
  18. The psd estimate.
  19. fgrid : array-like
  20. Frequency grid over which the periodogram was estimated.
  21.  
  22. Examples
  23. --------
  24. Generate a signal with two sinusoids,and compute its periodogram:
  25.  
  26. >>> fs = 1000
  27. >>> x = np.sin(2 * np.pi * 0.1 * fs * np.linspace(0,0.5,0.5*fs))
  28. >>> x += np.sin(2 * np.pi * 0.2 * fs * np.linspace(0,0.5*fs))
  29. >>> px,fx = periodogram(x,512,fs)
  30.  
  31. Notes
  32. -----
  33. Only real signals supported for Now.
  34.  
  35. Returns the one-sided version of the periodogram.
  36.  
  37. discrepency with matlab: matlab compute the psd in unit of power / radian /
  38. sample,and we compute the psd in unit of power / sample: to get the same
  39. result as matlab,just multiply the result from talkBox by 2pi"""
  40. x = np.atleast_1d(x)
  41. n = x.size
  42.  
  43. if x.ndim > 1:
  44. raise ValueError("Only rank 1 input supported for Now.")
  45. if not np.isrealobj(x):
  46. raise ValueError("Only real input supported for Now.")
  47. if not nfft:
  48. nfft = n
  49. if nfft < n:
  50. raise ValueError("nfft < signal size not supported yet")
  51.  
  52. pxx = np.abs(fft(x, nfft)) ** 2
  53. if nfft % 2 == 0:
  54. pn = nfft / 2 + 1
  55. else:
  56. pn = (nfft + 1 )/ 2
  57.  
  58. fgrid = np.linspace(0, fs * 0.5, pn)
  59. return pxx[:pn] / (n * fs), fgrid
项目:DeepFormants    作者:MLSpeech    | 项目源码 | 文件源码
  1. def arspec(x, fs=1):
  2. """Compute the spectral density using an AR model.
  3.  
  4. An AR model of the signal is estimated through the Yule-Walker equations;
  5. the estimated AR coefficient are then used to compute the spectrum,which
  6. can be computed explicitely for AR models.
  7.  
  8. Parameters
  9. ----------
  10. x : array-like
  11. input signal
  12. order : int
  13. Order of the LPC computation.
  14. nfft : int
  15. size of the fft to compute the periodogram. If None (default),is 1 (normalized frequency. e.g. 0.5 is the
  16. Nyquist limit).
  17.  
  18. Returns
  19. -------
  20. pxx : array-like
  21. The psd estimate.
  22. fgrid : array-like
  23. Frequency grid over which the periodogram was estimated.
  24. """
  25.  
  26. x = np.atleast_1d(x)
  27. n = x.size
  28.  
  29. if x.ndim > 1:
  30. raise ValueError("Only rank 1 input supported for Now.")
  31. if not np.isrealobj(x):
  32. raise ValueError("Only real input supported for Now.")
  33. if not nfft:
  34. nfft = n
  35. a, k = lpc(x, order)
  36.  
  37. # This is not enough to deal correctly with even/odd size
  38. if nfft % 2 == 0:
  39. pn = nfft / 2 + 1
  40. else:
  41. pn = (nfft + 1 )/ 2
  42.  
  43. px = 1 / np.fft.fft(a, nfft)[:pn]
  44. pxx = np.real(np.conj(px) * px)
  45. pxx /= fs / e
  46. fx = np.linspace(0, pxx.size)
  47. return pxx, fx
项目:decoding_challenge_cortana_2016_3rd    作者:kingjr    | 项目源码 | 文件源码
  1. def _write_raw_buffer(fid, buf, cals, fmt, inv_comp):
  2. """Write raw buffer
  3.  
  4. Parameters
  5. ----------
  6. fid : file descriptor
  7. an open raw data file.
  8. buf : array
  9. The buffer to write.
  10. cals : array
  11. Calibration factors.
  12. fmt : str
  13. ''short'',''int'',''single'',or ''double'' for 16/32 bit int or 32/64 bit
  14. float for each item. This will be doubled for complex datatypes. Note
  15. that short and int formats cannot be used for complex data.
  16. inv_comp : array | None
  17. The CTF compensation matrix used to revert compensation
  18. change when reading.
  19. """
  20. if buf.shape[0] != len(cals):
  21. raise ValueError(''buffer and calibration sizes do not match'')
  22.  
  23. if fmt not in [''short'', ''int'', ''single'', ''double'']:
  24. raise ValueError(''fmt must be "short","single",or "double"'')
  25.  
  26. if np.isrealobj(buf):
  27. if fmt == ''short'':
  28. write_function = write_dau_pack16
  29. elif fmt == ''int'':
  30. write_function = write_int
  31. elif fmt == ''single'':
  32. write_function = write_float
  33. else:
  34. write_function = write_double
  35. else:
  36. if fmt == ''single'':
  37. write_function = write_complex64
  38. elif fmt == ''double'':
  39. write_function = write_complex128
  40. else:
  41. raise ValueError(''only "single" and "double" supported for ''
  42. ''writing complex data'')
  43.  
  44. if inv_comp is not None:
  45. buf = np.dot(inv_comp / np.ravel(cals)[:, None], buf)
  46. else:
  47. buf = buf / np.ravel(cals)[:, None]
  48.  
  49. write_function(fid, FIFF.FIFF_DATA_BUFFER, buf)

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

本文标签: