温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

numpy中怎么使用squeeze函数

发布时间:2021-03-22 12:31:16 来源:亿速云 阅读:401 作者:小新 栏目:开发技术

这篇文章主要介绍了numpy中怎么使用squeeze函数,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

reshape函数:改变数组的维数(注意不是shape大小)

>>> e= np.arange(10)
>>> e
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> e.reshape(1,1,10)
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> e.reshape(1,1,10)
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> e.reshape(1,10,1)
array([[[0],
    [1],
    [2],
    [3],
    [4],
    [5],
    [6],
    [7],
    [8],
    [9]]])

squeeze 函数:从数组的形状中删除单维度条目,即把shape中为1的维度去掉

用法:numpy.squeeze(a,axis = None)

 1)a表示输入的数组;
 2)axis用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错;
 3)axis的取值可为None 或 int 或 tuple of ints, 可选。若axis为空,则删除所有单维度的条目;
 4)返回值:数组
 5) 不会修改原数组;

>>> a = e.reshape(1,1,10)
>>> a
array([[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]])
>>> np.squeeze(a)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

体现在画图时

>>> plt.plot(a)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 3240, in plot
  ret = ax.plot(*args, **kwargs)
 File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 1710, in inner
  return func(ax, *args, **kwargs)
 File "C:\Python27\lib\site-packages\matplotlib\axes\_axes.py", line 1437, in plot
  for line in self._get_lines(*args, **kwargs):
 File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 404, in _grab_next_args
  for seg in self._plot_args(this, kwargs):
 File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 384, in _plot_args
  x, y = self._xy_from_xy(x, y)
 File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 246, in _xy_from_xy
  "shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y can be no greater than 2-D, but have shapes (1L,) and (1L, 1L, 10L)
>>> plt.plot(np.squeeze(a))
[<matplotlib.lines.Line2D object at 0x00000000146CD940>]
>>> plt.show()

numpy中怎么使用squeeze函数

>>> np.squeeze(a).shape
(10L,)

通过np.squeeze()函数转换后,要显示的数组变成了秩为1的数组,即(10,)

感谢你能够认真阅读完这篇文章,希望小编分享的“numpy中怎么使用squeeze函数”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI