python⽣成指定长度的数组_python-numpy-03-创建特定形式
数组
1.np.arange创建指定步长
函数定义:def arange(start=None, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """
arange([start,] stop[, step,], dtype=None)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `numpy.linspace` for these cases.
Parameters
----------
start : number, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : number
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : number, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
Returns
-------
arange : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
"""
pass
说明:numpy.arange函数和经常使⽤的range函数⾮常的类似,只是多增加了⼀个dtype参数,dtype参数的作⽤和numpy.array⾥⾯介绍的作⽤是⼀致的。range()和arange()只所以这么灵活,⼀⽅⾯是python的灵活的参数机制;另⼀⽅⾯是对接收的参数数⽬进⾏判断,根据参数数⽬的不同执⾏不同的操作。
⽰例代码:# 指定终点
a = np.arange(10)
print(a)
print('--' * 20)
# 指定起点、终点
b = np.arange(1, 10)
print(b)
print('--' * 20)
# 指定起点、终点、步长
c = np.arange(1, 10, 2)
print(c)
print('--' * 20)
# 指定起点、终点、步长、dtype类型
d = np.arange(1, 10, 2, float)
print(d)
print('--' * 20)
# ⼩数的情况也能使⽤numpy,实际情况这样使⽤的⽐较少
e = np.arange(0.1, 1.0, 0.1, float)
print(e)
运⾏结果:[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. 3. 5. 7. 9.]
----------------------------------------
[0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
2.np.random.random创建随机数
⽤于创建值范围在[0.0, 1.0)区间的随机数组
函数定义:def random(size=None): # real signature unknown; restored from __doc__
"""
random(size=None)
Return random floats in the half-open interval [0.0, 1.0). Alias for
`random_sample` to ease forward-porting to the new random API.
"""
pass
通过介绍可以知道,random是random_sample的别名。我们再来看⼀下random_sample函数。def random_sample(size=None): # real signature unknown; restored from __doc__
"""
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the "continuous uniform" distribution over the
stated interval. To sample :math:`Unif[a, b), b > a` multiply
the output of `random_sample` by `(b-a)` and add `a`::
(b - a) * random_sample() + a
.. note::
New code should use the ``random`` method of a ``default_rng()``
instance instead; see `random-quick-start`.
Parameters
----------
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
linspace numpysingle value is returned.
Returns
-------
out : float or ndarray of floats
Array of random floats of shape `size` (unless ``size=None``, in which
case a single float is returned).
"""
pass
⽰例代码:import numpy as np
a1 = np.random.random(size=1)
a2 = np.random.random(size=(1,))
a3 = np.random.random_sample(size=(1,))
print(a1)
print("~~" * 10)
print(a2)
print("~~" * 10)
print(a3)
print('--' * 20)
b1 = np.random.random(size=(2, 3))
b2 = np.random.random_sample(size=(2, 3))
print(b1)
print("~~" * 10)
print(b2)
print("--" * 20)
运⾏结果:[0.12406671]
[0.51463238][0.89463238]
----------------------------------------
[[0.10907993 0.16789092 0.43668195]
[0.79106801 0.22137333 0.01017769]]
[[0.65803265 0.11789976 0.56492191]
[0.74975911 0.09096749 0.05589122]]程序说明:通过运⾏结果我们可以看到a1、a2、a3这三个结构⼀致,说明传递参数最终是以元组的形式进⾏解析的,另外⼀个就是random和random_sample效果⼀致。
> 为了程序规规范性,建议创建ndarray数组过程指定参数size以元组的形式传递。
### 3.np.random.randint创建随机整数
主要⽤于创建指定区间范围的整数数据类型数组
函数定义:
def randint(low, high=None, size=None, dtype=None): # real signature unknown; restored from doc""" randint(low, high=None, size=None, dtype=int)
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`).
.. note::
New code should use the ``integers`` method of a ``default_rng()``
instance instead; see `random-quick-start`.
Parameters
----------
low : int or array-like of ints
Lowest (signed) integers to be drawn from the distribution (unless
``high=None``, in which case this parameter is one above the
*highest* such integer).
high : int or array-like of ints, optional
If provided, one above the largest (signed) integer to be drawn
from the distribution (see above for behavior if ``high=None``).
If array-like, must contain integer values
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. Byteorder must be native.
The default value is 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.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。