翼度科技»论坛 编程开发 python 查看内容

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

1

主题

1

帖子

3

积分

新手上路

Rank: 1

积分
3
numpy多维数组的创建

多维数组(矩阵ndarray)
ndarray的基本属性

    1. shape
    复制代码
    维度的大小
    1. ndim
    复制代码
    维度的个数
    1. dtype
    复制代码
    数据类型

1.1 随机抽样创建

1.1.1 rand
生成指定维度的随机多维度浮点型数组,区间范围是[0,1)
  1. Random values in a given shape.
  2.             Create an array of the given shape and populate it with
  3.             random samples from a uniform distribution
  4.             over ``[0, 1)``.
  5. nd1 = np.random.rand(1,1)
  6. print(nd1)
  7. print('维度的个数',nd1.ndim)
  8. print('维度的大小',nd1.shape)
  9. print('数据类型',nd1.dtype)   # float 64
复制代码
1.1.2 uniform
  1. def uniform(low=0.0, high=1.0, size=None): # real signature unknown; restored from __doc__
  2.     """
  3.     uniform(low=0.0, high=1.0, size=None)
  4.             Draw samples from a uniform distribution.
  5.             Samples are uniformly distributed over the half-open interval
  6.             ``[low, high)`` (includes low, but excludes high).  In other words,
  7.             any value within the given interval is equally likely to be drawn
  8.             by `uniform`.
  9.             Parameters
  10.             ----------
  11.             low : float or array_like of floats, optional
  12.                 Lower boundary of the output interval.  All values generated will be
  13.                 greater than or equal to low.  The default value is 0.
  14.             high : float or array_like of floats
  15.                 Upper boundary of the output interval.  All values generated will be
  16.                 less than high.  The default value is 1.0.
  17.             size : int or tuple of ints, optional
  18.                 Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
  19.                 ``m * n * k`` samples are drawn.  If size is ``None`` (default),
  20.                 a single value is returned if ``low`` and ``high`` are both scalars.
  21.                 Otherwise, ``np.broadcast(low, high).size`` samples are drawn.
  22.             Returns
  23.             -------
  24.             out : ndarray or scalar
  25.                 Drawn samples from the parameterized uniform distribution.
  26.             See Also
  27.             --------
  28.             randint : Discrete uniform distribution, yielding integers.
  29.             random_integers : Discrete uniform distribution over the closed
  30.                               interval ``[low, high]``.
  31.             random_sample : Floats uniformly distributed over ``[0, 1)``.
  32.             random : Alias for `random_sample`.
  33.             rand : Convenience function that accepts dimensions as input, e.g.,
  34.                    ``rand(2,2)`` would generate a 2-by-2 array of floats,
  35.                    uniformly distributed over ``[0, 1)``.
  36.             Notes
  37.             -----
  38.             The probability density function of the uniform distribution is
  39.             .. math:: p(x) = \frac{1}{b - a}
  40.             anywhere within the interval ``[a, b)``, and zero elsewhere.
  41.             When ``high`` == ``low``, values of ``low`` will be returned.
  42.             If ``high`` < ``low``, the results are officially undefined
  43.             and may eventually raise an error, i.e. do not rely on this
  44.             function to behave when passed arguments satisfying that
  45.             inequality condition.
  46.             Examples
  47.             --------
  48.             Draw samples from the distribution:
  49.             >>> s = np.random.uniform(-1,0,1000)
  50.             All values are within the given interval:
  51.             >>> np.all(s >= -1)
  52.             True
  53.             >>> np.all(s < 0)
  54.             True
  55.             Display the histogram of the samples, along with the
  56.             probability density function:
  57.             >>> import matplotlib.pyplot as plt
  58.             >>> count, bins, ignored = plt.hist(s, 15, density=True)
  59.             >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
  60.             >>> plt.show()
  61.     """
  62.     pass
复制代码
  1. nd2 = np.random.uniform(-1,5,size = (2,3))
  2. print(nd2)
  3. print('维度的个数',nd2.ndim)
  4. print('维度的大小',nd2.shape)
  5. print('数据类型',nd2.dtype)
复制代码
运行结果:

1.1.3 randint
  1. def randint(low, high=None, size=None, dtype='l'): # real signature unknown; restored from __doc__
  2.     """
  3.     randint(low, high=None, size=None, dtype='l')
  4.             Return random integers from `low` (inclusive) to `high` (exclusive).
  5.             Return random integers from the "discrete uniform" distribution of
  6.             the specified dtype in the "half-open" interval [`low`, `high`). If
  7.             `high` is None (the default), then results are from [0, `low`).
  8.             Parameters
  9.             ----------
  10.             low : int
  11.                 Lowest (signed) integer to be drawn from the distribution (unless
  12.                 ``high=None``, in which case this parameter is one above the
  13.                 *highest* such integer).
  14.             high : int, optional
  15.                 If provided, one above the largest (signed) integer to be drawn
  16.                 from the distribution (see above for behavior if ``high=None``).
  17.             size : int or tuple of ints, optional
  18.                 Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
  19.                 ``m * n * k`` samples are drawn.  Default is None, in which case a
  20.                 single value is returned.
  21.             dtype : dtype, optional
  22.                 Desired dtype of the result. All dtypes are determined by their
  23.                 name, i.e., 'int64', 'int', etc, so byteorder is not available
  24.                 and a specific precision may have different C types depending
  25.                 on the platform. The default value is 'np.int'.
  26.                 .. versionadded:: 1.11.0
  27.             Returns
  28.             -------
  29.             out : int or ndarray of ints
  30.                 `size`-shaped array of random integers from the appropriate
  31.                 distribution, or a single such random int if `size` not provided.
  32.             See Also
  33.             --------
  34.             random.random_integers : similar to `randint`, only for the closed
  35.                 interval [`low`, `high`], and 1 is the lowest value if `high` is
  36.                 omitted. In particular, this other one is the one to use to generate
  37.                 uniformly distributed discrete non-integers.
  38.             Examples
  39.             --------
  40.             >>> np.random.randint(2, size=10)
  41.             array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
  42.             >>> np.random.randint(1, size=10)
  43.             array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
  44.             Generate a 2 x 4 array of ints between 0 and 4, inclusive:
  45.             >>> np.random.randint(5, size=(2, 4))
  46.             array([[4, 0, 2, 1],
  47.                    [3, 2, 2, 0]])
  48.     """
  49.     pass
复制代码
  1. nd3 = np.random.randint(1,20,size=(3,4))
  2. print(nd3)
  3. print('维度的个数',nd3.ndim)
  4. print('维度的大小',nd3.shape)
  5. print('数据类型',nd3.dtype)
  6. 展示:
  7. [[11 17  5  6]
  8. [17  1 12  2]
  9. [13  9 10 16]]
  10. 维度的个数 2
  11. 维度的大小 (3, 4)
  12. 数据类型 int32
复制代码
注意点:
1、如果没有指定最大值,只是指定了最小值,范围是[0,最小值)
2、如果有最小值,也有最大值,范围为[最小值,最大值)

1.2 序列创建

1.2.1 array
  1. 通过列表进行创建
  2. nd4 = np.array([1,2,3])
  3. 展示:
  4. [1 2 3]
  5. 通过列表嵌套列表创建
  6. nd5 = np.array([[1,2,3],[4,5]])
  7. 展示:
  8. [list([1, 2, 3]) list([4, 5])]
  9. 综合
  10. nd4 = np.array([1,2,3])
  11. print(nd4)
  12. print(nd4.ndim)
  13. print(nd4.shape)
  14. print(nd4.dtype)
  15. nd5 = np.array([[1,2,3],[4,5,6]])
  16. print(nd5)
  17. print(nd5.ndim)
  18. print(nd5.shape)
  19. print(nd5.dtype)
  20. 展示:
  21. [1 2 3]
  22. 1
  23. (3,)
  24. int32
  25. [[1 2 3]
  26. [4 5 6]]
  27. 2
  28. (2, 3)
  29. int32
复制代码
1.2.2 zeros
  1. nd6 = np.zeros((4,4))
  2. print(nd6)
  3. 展示:
  4. [[0. 0. 0. 0.]
  5. [0. 0. 0. 0.]
  6. [0. 0. 0. 0.]
  7. [0. 0. 0. 0.]]
  8. 注意点:
  9. 1、创建的数里面的数据为0
  10. 2、默认的数据类型是float
  11. 3、可以指定其他的数据类型
复制代码
1.2.3 ones
  1. nd7 = np.ones((4,4))
  2. print(nd7)
  3. 展示:
  4. [[1. 1. 1. 1.]
  5. [1. 1. 1. 1.]
  6. [1. 1. 1. 1.]
  7. [1. 1. 1. 1.]]
复制代码
1.2.4 arange
  1. nd8 = np.arange(10)
  2. print(nd8)
  3. nd9 = np.arange(1,10)
  4. print(nd9)
  5. nd10 = np.arange(1,10,2)
  6. print(nd10)
复制代码
结果:
  1. [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 数组重新排列
  1. nd11 = np.arange(10)
  2. print(nd11)
  3. nd12 = nd11.reshape(2,5)
  4. print(nd12)
  5. print(nd11)
  6. 展示:
  7. [0 1 2 3 4 5 6 7 8 9]
  8. [[0 1 2 3 4]
  9. [5 6 7 8 9]]
  10. [0 1 2 3 4 5 6 7 8 9]
  11. 注意点:
  12. 1、有返回值,返回新的数组,原始数组不受影响
  13. 2、进行维度大小的设置过程中,要注意数据的个数,注意元素的个数
  14. nd13 = np.arange(10)
  15. print(nd13)
  16. nd14 = np.random.shuffle(nd13)
  17. print(nd14)
  18. print(nd13)
  19. 展示:
  20. [0 1 2 3 4 5 6 7 8 9]
  21. None
  22. [8 2 6 7 9 3 5 1 0 4]
  23. 注意点:
  24. 1、在原始数据集上做的操作
  25. 2、将原始数组的元素进行重新排列,打乱顺序
  26. 3、shuffle这个是没有返回值的
复制代码
两个可以配合使用,先打乱,在重新排列

1.4 数据类型的转换
  1. nd15 = np.arange(10,dtype=np.int64)
  2. print(nd15)
  3. nd16 = nd15.astype(np.float64)
  4. print(nd16)
  5. print(nd15)
  6. 展示:
  7. [0 1 2 3 4 5 6 7 8 9]
  8. [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
  9. [0 1 2 3 4 5 6 7 8 9]
  10. 注意点:
  11. 1、astype()不在原始数组做操作,有返回值,返回的是更改数据类型的新数组
  12. 2、在创建新数组的过程中,有dtype参数进行指定
复制代码
1.5 数组转列表
  1. arr1 = np.arange(10)
  2. # 数组转列表
  3. print(list(arr1))
  4. print(arr1.tolist())
  5. 展示:
  6. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  7. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
复制代码
numpy 多维数组相关问题


创建(多维)数组
  1. x = np.zeros(shape=[10, 1000, 1000], dtype='int')
复制代码

得到全零的多维数组。

数组赋值
  1. x[*,*,*] = ***
复制代码
np数组保存
  1. np.save("./**.npy",x)
复制代码
读取np数组
  1. x = np.load("path")
复制代码
总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源:https://www.jb51.net/article/283847.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具