GVKun编程网logo

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

2

本文将带您了解关于Pythonnumpy模块-ComplexWarning()实例源码的新内容,同时我们还将为您解释python中numpy模块的相关知识,另外,我们还将为您提供关于ComplexWa

本文将带您了解关于Python numpy 模块-ComplexWarning() 实例源码的新内容,同时我们还将为您解释python中numpy模块的相关知识,另外,我们还将为您提供关于ComplexWarning:将复数值转换为实数会丢弃虚部、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()的实用信息。

本文目录一览:

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

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

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

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

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_ticket_1539(self):
  2. dtypes = [x for x in np.typeDict.values()
  3. if (issubclass(x, np.number)
  4. and not issubclass(x, np.timedelta64))]
  5. a = np.array([], dtypes[0])
  6. failures = []
  7. # ignore complex warnings
  8. with warnings.catch_warnings():
  9. warnings.simplefilter(''ignore'', np.ComplexWarning)
  10. for x in dtypes:
  11. b = a.astype(x)
  12. for y in dtypes:
  13. c = a.astype(y)
  14. try:
  15. np.dot(b, c)
  16. except TypeError:
  17. failures.append((x, y))
  18. if failures:
  19. raise AssertionError("Failures: %r" % failures)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 63)
  4. bool_index = np.zeros(shape).astype(bool)
  5. bool_index[0, 1] = True
  6. zero_array = np.zeros(shape)
  7.  
  8. # Assigning float is fine.
  9. zero_array[bool_index] = np.array([1])
  10. assert_equal(zero_array[0, 1], 1)
  11.  
  12. # Fancy indexing works,although we get a cast warning.
  13. assert_warns(np.ComplexWarning,
  14. zero_array.__setitem__, ([0], [1]), np.array([2 + 1j]))
  15. assert_equal(zero_array[0, 2) # No complex part
  16.  
  17. # Cast complex to float,throwing away the imaginary portion.
  18. assert_warns(np.ComplexWarning, bool_index, np.array([1j]))
  19. assert_equal(zero_array[0, 0)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_ticket_1539(self):
  2. dtypes = [x for x in np.typeDict.values()
  3. if (issubclass(x, y))
  4. if failures:
  5. raise AssertionError("Failures: %r" % failures)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 0)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_ticket_1539(self):
  2. dtypes = [x for x in np.typeDict.values()
  3. if (issubclass(x, y))
  4. if failures:
  5. raise AssertionError("Failures: %r" % failures)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 0)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_ticket_1539(self):
  2. dtypes = [x for x in np.typeDict.values()
  3. if (issubclass(x, y))
  4. if failures:
  5. raise AssertionError("Failures: %r" % failures)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 0)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_ticket_1539(self):
  2. dtypes = [x for x in np.typeDict.values()
  3. if (issubclass(x, y))
  4. if failures:
  5. raise AssertionError("Failures: %r" % failures)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 0)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 0)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_dtype_from_dtype(self):
  2. mat = np.eye(3)
  3. codes = ''efdgFDG''
  4. for nf, rf in zip(self.nanfuncs, self.stdfuncs):
  5. for c in codes:
  6. with suppress_warnings() as sup:
  7. if nf in {np.nanstd, np.nanvar} and c in ''FDG'':
  8. # Giving the warning is a small bug,see gh-8000
  9. sup.filter(np.ComplexWarning)
  10. tgt = rf(mat, dtype=np.dtype(c), axis=1).dtype.type
  11. res = nf(mat, axis=1).dtype.type
  12. assert_(res is tgt)
  13. # scalar case
  14. tgt = rf(mat, axis=None).dtype.type
  15. res = nf(mat, axis=None).dtype.type
  16. assert_(res is tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_ddof_too_big(self):
  2. nanfuncs = [np.nanvar, np.nanstd]
  3. stdfuncs = [np.var, np.std]
  4. dsize = [len(d) for d in _rdat]
  5. for nf, rf in zip(nanfuncs, stdfuncs):
  6. for ddof in range(5):
  7. with suppress_warnings() as sup:
  8. sup.record(RuntimeWarning)
  9. sup.filter(np.ComplexWarning)
  10. tgt = [ddof >= d for d in dsize]
  11. res = nf(_ndat, axis=1, ddof=ddof)
  12. assert_equal(np.isnan(res), tgt)
  13. if any(tgt):
  14. assert_(len(sup.log) == 1)
  15. else:
  16. assert_(len(sup.log) == 0)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def perform(self, node, inputs, outputs):
  2. # Kalbfleisch and Lawless,J. Am. Stat. Assoc. 80 (1985) Equation 3.4
  3. # Kind of... You need to do some algebra from there to arrive at
  4. # this expression.
  5. (A, gA) = inputs
  6. (out,) = outputs
  7. w, V = scipy.linalg.eig(A, right=True)
  8. U = scipy.linalg.inv(V).T
  9.  
  10. exp_w = numpy.exp(w)
  11. X = numpy.subtract.outer(exp_w, exp_w) / numpy.subtract.outer(w, w)
  12. numpy.fill_diagonal(X, exp_w)
  13. Y = U.dot(V.T.dot(gA).dot(U) * X).dot(V.T)
  14.  
  15. with warnings.catch_warnings():
  16. warnings.simplefilter("ignore", numpy.ComplexWarning)
  17. out[0] = Y.astype(A.dtype)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_ticket_1539(self):
  2. dtypes = [x for x in np.typeDict.values()
  3. if (issubclass(x, y))
  4. if failures:
  5. raise AssertionError("Failures: %r" % failures)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_boolean_index_cast_assign(self):
  2. # Setup the boolean index and float arrays.
  3. shape = (8, 0)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, np.cdouble, np.clongdouble]:
  3. x = tp(1+2j)
  4. assert_warns(np.ComplexWarning, float, x)
  5. with warnings.catch_warnings():
  6. warnings.simplefilter(''ignore'')
  7. assert_equal(float(x), float(x.real))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, dtype=''f4'').newbyteorder().byteswap()
  5. i = nditer(a, [''buffered'', ''external_loop''],
  6. [[''readwrite'', ''nbo'', ''aligned'']],
  7. casting=''same_kind'',
  8. op_dtypes=[np.dtype(''f8'').newbyteorder()],
  9. buffersize=3)
  10. for v in i:
  11. v[...] *= 2
  12.  
  13. assert_equal(a, 2*np.arange(10, dtype=''f4''))
  14.  
  15. try:
  16. warnings.simplefilter("ignore", np.ComplexWarning)
  17.  
  18. a = np.arange(10, dtype=''f8'').newbyteorder().byteswap()
  19. i = nditer(a,
  20. [[''readwrite'',
  21. casting=''unsafe'',
  22. op_dtypes=[np.dtype(''c8'').newbyteorder()],
  23. buffersize=3)
  24. for v in i:
  25. v[...] *= 2
  26.  
  27. assert_equal(a, dtype=''f8''))
  28. finally:
  29. warnings.simplefilter("default", np.ComplexWarning)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
  3. y = np.array([1-2j, 1+2j])
  4.  
  5. with warnings.catch_warnings():
  6. warnings.simplefilter("error", np.ComplexWarning)
  7. assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y)
  8. assert_equal(x, [1, 2])
项目:cupy    作者:cupy    | 项目源码 | 文件源码
  1. def test_pad_default(self, xp, dtype):
  2. array = xp.array(self.array, dtype=dtype)
  3.  
  4. # Older version of NumPy(<1.12) can emit ComplexWarning
  5. def f():
  6. return xp.pad(array, self.pad_width, mode=self.mode)
  7.  
  8. if xp is numpy:
  9. with warnings.catch_warnings():
  10. warnings.simplefilter(''ignore'', numpy.ComplexWarning)
  11. return f()
  12. else:
  13. return f()
项目:cupy    作者:cupy    | 项目源码 | 文件源码
  1. def test_pad(self, mode=self.mode,
  2. constant_values=self.constant_values)
  3.  
  4. if xp is numpy:
  5. with warnings.catch_warnings():
  6. warnings.simplefilter(''ignore'', numpy.ComplexWarning)
  7. return f()
  8. else:
  9. return f()
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, float(x.real))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, np.ComplexWarning)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, float(x.real))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, np.ComplexWarning)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, float(x.real))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, np.ComplexWarning)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, float(x.real))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, np.ComplexWarning)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, x)
  3. with suppress_warnings() as sup:
  4. sup.filter(np.ComplexWarning)
  5. assert_equal(float(x), float(x.real))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, dtype=''f4''))
  5.  
  6. with suppress_warnings() as sup:
  7. sup.filter(np.ComplexWarning)
  8.  
  9. a = np.arange(10, dtype=''f8''))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_complex_scalar_warning(self):
  2. for tp in [np.csingle, float(x.real))
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_iter_buffered_cast_byteswapped():
  2. # Test that buffering can handle a cast which requires swap->cast->swap
  3.  
  4. a = np.arange(10, np.ComplexWarning)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_complex_warning(self):
  2. x = np.array([1, 2])
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def conv(self, img, kern, mode="valid", dilation=1):
  2. """
  3. Basic slow Python 2D or 3D convolution for DebugMode
  4. """
  5.  
  6. if not imported_scipy_signal:
  7. raise NotImplementedError(
  8. "AbstractConv perform requires the python package"
  9. " for scipy.signal to be installed.")
  10. if not (mode in (''valid'', ''full'')):
  11. raise ValueError(
  12. ''invalid mode {},which must be either ''
  13. ''"valid" or "full"''.format(mode))
  14. if isinstance(dilation, integer_types):
  15. dilation = (dilation,) * self.convdim
  16. if len(dilation) != self.convdim:
  17. raise ValueError(
  18. ''invalid dilation {},expected {} values''.format(dilation,
  19. self.convdim))
  20.  
  21. out_shape = get_conv_output_shape(img.shape, kern.shape,
  22. mode, [1] * self.convdim, dilation)
  23.  
  24. out = numpy.zeros(out_shape, dtype=img.dtype)
  25. dil_kern_shp = kern.shape[:-self.convdim] + tuple(
  26. (kern.shape[-self.convdim + i] - 1) * dilation[i] + 1
  27. for i in range(self.convdim))
  28. dilated_kern = numpy.zeros(dil_kern_shp, dtype=kern.dtype)
  29. dilated_kern[(slice(None), slice(None)) +
  30. tuple(slice(None, None, dilation[i]) for i in range(self.convdim))
  31. ] = kern
  32.  
  33. if self.convdim == 2:
  34. val = _valfrommode(mode)
  35. bval = _bvalfromboundary(''fill'')
  36.  
  37. with warnings.catch_warnings():
  38. warnings.simplefilter(''ignore'', numpy.ComplexWarning)
  39. for b in xrange(img.shape[0]):
  40. for n in xrange(kern.shape[0]):
  41. for im0 in xrange(img.shape[1]):
  42. # some cast generates a warning here
  43. out[b, n, ...] += _convolve2d(img[b, im0, ...],
  44. dilated_kern[n,
  45. 1, val, bval, 0)
  46. elif self.convdim == 3:
  47. for b in xrange(img.shape[0]):
  48. for n in xrange(kern.shape[0]):
  49. for im0 in xrange(img.shape[1]):
  50. out[b, ...] += convolve(img[b,
  51. dilated_kern[n,
  52. mode)
  53. else:
  54. raise NotImplementedError(''only 2D and 3D convolution are implemented'')
  55. return out

ComplexWarning:将复数值转换为实数会丢弃虚部

ComplexWarning:将复数值转换为实数会丢弃虚部

如何解决ComplexWarning:将复数值转换为实数会丢弃虚部?

我想知道如何解决这个问题。

我想用matplotlib.pyplot绘制一个复杂的函数。

Python显示了不正确的图形,因此显示以下内容:

返回数组(a,dtype,copy = False,order = order)

ComplexWarning:将复杂值转换为实数会丢弃虚部

import numpy as np
import matplotlib.pyplot as plt

def f(time):
    function=(1+time)+ 1j*(1-time)
    return function

x = plt.subplot()
time= np.arange(0,np.pi*2,0.2,dtype="complex_")

plt.plot(time,f(time),lw=2,color="violet",linestyle= "-")


plt.title("Gráfica",fontsize=20,color="violet")

plt.xlabel("Time")
plt.ylabel("Complex Number")
plt.show()

解决方法

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

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

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

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)

 

我们今天的关于Python numpy 模块-ComplexWarning() 实例源码python中numpy模块的分享已经告一段落,感谢您的关注,如果您想了解更多关于ComplexWarning:将复数值转换为实数会丢弃虚部、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()的相关信息,请在本站查询。

本文标签: