iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >numpy之多维数组的创建全过程
  • 558
分享到

numpy之多维数组的创建全过程

numpy多维数组numpy多维数组创建numpy创建多维数组 2023-05-12 14:05:28 558人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录numpy多维数组的创建1.1 随机抽样创建1.2 序列创建1.3 数组重新排列1.4 数据类型的转换1.5 数组转列表numpy 多维数组相关问题创建(多维)数组数组赋值np数

numpy多维数组的创建

多维数组(矩阵ndarray)

ndarray的基本属性

  • shape维度的大小
  • ndim维度的个数
  • dtype数据类型

1.1 随机抽样创建

1.1.1 rand

生成指定维度的随机多维度浮点型数组,区间范围是[0,1)

Random values in a given shape.
            Create an array of the given shape and populate it with
            random samples from a unifORM distribution
            over ``[0, 1)``.
nd1 = np.random.rand(1,1)
print(nd1)
print('维度的个数',nd1.ndim)
print('维度的大小',nd1.shape)
print('数据类型',nd1.dtype)   # float 64

1.1.2 uniform

def uniform(low=0.0, high=1.0, size=None): # real signature unknown; restored from __doc__
    """
    uniform(low=0.0, high=1.0, size=None)
            Draw samples from a uniform distribution.
            Samples are uniformly distributed over the half-open interval
            ``[low, high)`` (includes low, but excludes high).  In other Words,
            any value within the given interval is equally likely to be drawn
            by `uniform`.
            Parameters
            ----------
            low : float or array_like of floats, optional
                Lower boundary of the output interval.  All values generated will be
                greater than or equal to low.  The default value is 0.
            high : float or array_like of floats
                Upper boundary of the output interval.  All values generated will be
                less than high.  The default value is 1.0.
            size : int or tuple of ints, optional
                Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
                ``m * n * k`` samples are drawn.  If size is ``None`` (default),
                a single value is returned if ``low`` and ``high`` are both Scalars.
                Otherwise, ``np.broadcast(low, high).size`` samples are drawn.
            Returns
            -------
            out : ndarray or scalar
                Drawn samples from the parameterized uniform distribution.
            See Also
            --------
            randint : Discrete uniform distribution, yielding integers.
            random_integers : Discrete uniform distribution over the closed
                              interval ``[low, high]``.
            random_sample : Floats uniformly distributed over ``[0, 1)``.
            random : Alias for `random_sample`.
            rand : Convenience function that accepts dimensions as input, e.g.,
                   ``rand(2,2)`` would generate a 2-by-2 array of floats,
                   uniformly distributed over ``[0, 1)``.
            Notes
            -----
            The probability density function of the uniform distribution is
            .. math:: p(x) = \frac{1}{b - a}
            anywhere within the interval ``[a, b)``, and zero elsewhere.
            When ``high`` == ``low``, values of ``low`` will be returned.
            If ``high`` < ``low``, the results are officially undefined
            and may eventually raise an error, i.e. do not rely on this
            function to behave when passed arguments satisfying that
            inequality condition.
            Examples
            --------
            Draw samples from the distribution:
            >>> s = np.random.uniform(-1,0,1000)
            All values are within the given interval:
            >>> np.all(s >= -1)
            True
            >>> np.all(s < 0)
            True
            Display the histogram of the samples, along with the
            probability density function:
            >>> import matplotlib.pyplot as plt
            >>> count, bins, ignored = plt.hist(s, 15, density=True)
            >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
            >>> plt.show()
    """
    pass
nd2 = np.random.uniform(-1,5,size = (2,3))
print(nd2)
print('维度的个数',nd2.ndim)
print('维度的大小',nd2.shape)
print('数据类型',nd2.dtype)

运行结果:

在这里插入图片描述

1.1.3 randint

def randint(low, high=None, size=None, dtype='l'): # real signature unknown; restored from __doc__
    """
    randint(low, high=None, size=None, dtype='l')
            Return random integers from `low` (inclusive) to `high` (exclusive).
            Return random integers from the "discrete uniform" distribution of
            the specified dtype in the "half-open" interval [`low`, `high`). If
            `high` is None (the default), then results are from [0, `low`).
            Parameters
            ----------
            low : int
                Lowest (signed) integer to be drawn from the distribution (unless
                ``high=None``, in which case this parameter is one above the
                *highest* such integer).
            high : int, optional
                If provided, one above the largest (signed) integer to be drawn
                from the distribution (see above for behavior if ``high=None``).
            size : int or tuple of ints, optional
                Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
                ``m * n * k`` samples are drawn.  Default is None, in which case a
                single value is returned.
            dtype : dtype, optional
                Desired dtype of the result. All dtypes are determined by their
                name, i.e., 'int64', 'int', etc, so byteorder is not available
                and a specific precision may have different C types depending
                on the platform. The default value is 'np.int'.
                .. versionadded:: 1.11.0
            Returns
            -------
            out : int or ndarray of ints
                `size`-shaped array of random integers from the appropriate
                distribution, or a single such random int if `size` not provided.
            See Also
            --------
            random.random_integers : similar to `randint`, only for the closed
                interval [`low`, `high`], and 1 is the lowest value if `high` is
                omitted. In particular, this other one is the one to use to generate
                uniformly distributed discrete non-integers.
            Examples
            --------
            >>> np.random.randint(2, size=10)
            array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
            >>> np.random.randint(1, size=10)
            array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
            Generate a 2 x 4 array of ints between 0 and 4, inclusive:
            >>> np.random.randint(5, size=(2, 4))
            array([[4, 0, 2, 1],
                   [3, 2, 2, 0]])
    """
    pass
nd3 = np.random.randint(1,20,size=(3,4))
print(nd3)
print('维度的个数',nd3.ndim)
print('维度的大小',nd3.shape)
print('数据类型',nd3.dtype)
展示:
[[11 17  5  6]
 [17  1 12  2]
 [13  9 10 16]]
维度的个数 2
维度的大小 (3, 4)
数据类型 int32

注意点:

1、如果没有指定最大值,只是指定了最小值,范围是[0,最小值)

2、如果有最小值,也有最大值,范围为[最小值,最大值)

1.2 序列创建

1.2.1 array

通过列表进行创建
nd4 = np.array([1,2,3])
展示:
[1 2 3]
通过列表嵌套列表创建
nd5 = np.array([[1,2,3],[4,5]])
展示:
[list([1, 2, 3]) list([4, 5])]
综合
nd4 = np.array([1,2,3])
print(nd4)
print(nd4.ndim)
print(nd4.shape)
print(nd4.dtype)
nd5 = np.array([[1,2,3],[4,5,6]])
print(nd5)
print(nd5.ndim)
print(nd5.shape)
print(nd5.dtype)
展示:
[1 2 3]
1
(3,)
int32
[[1 2 3]
 [4 5 6]]
2
(2, 3)
int32

1.2.2 zeros

nd6 = np.zeros((4,4))
print(nd6)
展示:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
注意点:
1、创建的数里面的数据为0
2、默认的数据类型是float
3、可以指定其他的数据类型

1.2.3 ones

nd7 = np.ones((4,4))
print(nd7)
展示:
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]

1.2.4 arange

nd8 = np.arange(10)
print(nd8)
nd9 = np.arange(1,10)
print(nd9)
nd10 = np.arange(1,10,2)
print(nd10)

结果:

[0 1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 3 5 7 9]

注意点:

  • 1、只填写一位数,范围:[0,填写的数字)
  • 2、填写两位,范围:[最低位,最高位)
  • 3、填写三位,填写的是(最低位,最高位,步长)
  • 4、创建的是一位数组
  • 5、等同于np.array(range())

1.3 数组重新排列

nd11 = np.arange(10)
print(nd11)
nd12 = nd11.reshape(2,5)
print(nd12)
print(nd11)
展示:
[0 1 2 3 4 5 6 7 8 9]
[[0 1 2 3 4]
 [5 6 7 8 9]]
[0 1 2 3 4 5 6 7 8 9]
注意点:
1、有返回值,返回新的数组,原始数组不受影响
2、进行维度大小的设置过程中,要注意数据的个数,注意元素的个数
nd13 = np.arange(10)
print(nd13)
nd14 = np.random.shuffle(nd13)
print(nd14)
print(nd13)
展示:
[0 1 2 3 4 5 6 7 8 9]
None
[8 2 6 7 9 3 5 1 0 4]
注意点:
1、在原始数据集上做的操作
2、将原始数组的元素进行重新排列,打乱顺序
3、shuffle这个是没有返回值的

两个可以配合使用,先打乱,在重新排列

1.4 数据类型的转换

nd15 = np.arange(10,dtype=np.int64)
print(nd15)
nd16 = nd15.astype(np.float64)
print(nd16)
print(nd15)
展示:
[0 1 2 3 4 5 6 7 8 9]
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[0 1 2 3 4 5 6 7 8 9]
注意点:
1、astype()不在原始数组做操作,有返回值,返回的是更改数据类型的新数组
2、在创建新数组的过程中,有dtype参数进行指定

1.5 数组转列表

arr1 = np.arange(10)
# 数组转列表
print(list(arr1))
print(arr1.tolist())
展示:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

numpy 多维数组相关问题

创建(多维)数组

x = np.zeros(shape=[10, 1000, 1000], dtype='int')

得到全零的多维数组。

数组赋值

x[*,*,*] = ***

np数组保存

np.save("./**.npy",x)

读取np数组

x = np.load("path")

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: numpy之多维数组的创建全过程

本文链接: https://www.lsjlt.com/news/202115.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • numpy之多维数组的创建全过程
    目录numpy多维数组的创建1.1 随机抽样创建1.2 序列创建1.3 数组重新排列1.4 数据类型的转换1.5 数组转列表numpy 多维数组相关问题创建(多维)数组数组赋值np数...
    99+
    2023-05-12
    numpy多维数组 numpy多维数组创建 numpy创建多维数组
  • Python NumPy教程之数组的创建详解
    本篇文章给大家带来了关于Python的相关知识,主要为大家详细介绍了Python NumPy中数组的创建方式,文中的示例代码讲解详细,对我们学习Python有一定帮助,需要的可以参考一下。【相关推荐:Python3视频教程 】使用 List...
    99+
    2022-08-26
  • Python 用NumPy创建二维数组的案例
    前言 上位机实战开发先放一放,今天来学习一个新的内容—NumPy的使用 1 一维数组 例:用普通方法生成一维数组 num = [0 for i in range(1,5)] # ...
    99+
    2022-11-11
  • python创建多维数组的3种方式:
    python创建多维数组的3种方式:#coding=utf-8 import numpy as np #1 image =[[(col+1)*(row+1) for col in range(5)] for row in range(3)...
    99+
    2023-01-31
    多维 数组 方式
  • Python入门教程(四十)Python的NumPy数组创建
    目录创建 NumPy ndarray 对象数组中的维0-D 数组1-D 数组2-D 数组3-D 数组检查维数?更高维的数组创建 NumPy ndarray 对象 NumPy 用于处理...
    99+
    2023-05-12
    Python NumPy 数组 NumPy 数组创建
  • C#动态创建数组的实现过程
    本篇内容主要讲解“C#动态创建数组的实现过程”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C#动态创建数组的实现过程”吧!C#动态创建数组在实际开发中是十分实用的功能实现,那么C#动态创建数组是...
    99+
    2023-06-17
  • Node.js视频流应用创建之后端的全过程
    目录前言初始化主体逻辑总结前言 在本文中,将展示一个非常简单的 Node.js 应用程序,用于在线流媒体视频传输。本文仅涵盖后端,在下一部分中,将使用 Vue.js 创建前端。话不多...
    99+
    2022-11-13
  • Python学习教程:Numpy系列,创建数组的三大绝招
    周一啦,工作使我快乐使我开心,这一期的Python学习教程想跟大家讲一下Numpy系列,创建数组的三大绝招,绝招哈,都传授给你们啦!创建Numpy数组的三大绝招使用函数np.array使用便捷的内置函数使用随机库函数Numpy库的核心对象便...
    99+
    2023-06-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作