www.91084.com

GVKun编程网logo

python-numpy-03-创建特定形式数组(numpy中创建特定数组的方法)

2

对于python-numpy-03-创建特定形式数组感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍numpy中创建特定数组的方法,并为您提供关于"importnumpyasnp"ImportE

对于python-numpy-03-创建特定形式数组感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍numpy中创建特定数组的方法,并为您提供关于"import numpy as np" ImportError: No module named numpy、3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数、Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、Difference between import numpy and import numpy as np的有用信息。

本文目录一览:

python-numpy-03-创建特定形式数组(numpy中创建特定数组的方法)

python-numpy-03-创建特定形式数组(numpy中创建特定数组的方法)

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.
        numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
        numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
    """
    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
                single 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. 
"""
pass

说明:

1. 参数`low`和参数`high`使用类似于random函数的使用方法
2. size用法和上面random函数介绍的一样,建议使用元组
3. dtype函数用于指定数据类型,注意:**因为randint本身已经指定整数类型的范围,所以不能指定非整形数据类型。**

示例代码:

import numpy as np

指定终点

a1 = np.random.randint(10)
print(a1)
print(''--'' * 20)

指定起点、终点

b1 = np.random.randint(1, 10)
print(b1)
print(''--'' * 20)

指定起点、终点、大小

c1 = np.random.randint(1, 10, size=(2, 3))
print(c1)
print(''--'' * 20)

指定起点、终点、大小、数据类型

d1 = np.random.randint(1, 10, size=(2, 3), dtype=np.uint8)
print(d1)
print(''--'' * 20)


运行结果:

9

9

[[9 8 6]

[1 1 5]]

[[6 3 8]

[9 9 5]]




### 4.创建正态分布数组

#### 4.1 np.random.randn创建标准正太分布

用于创建符合标准正态分布(期望为0,方差为1)

函数定义

def randn(*dn): # known case of numpy.random.mtrand.randn

"""
randn(d0, d1, ..., dn)

        Return a sample (or samples) from the "standard normal" distribution.

        .. note::
            This is a convenience function for users porting code from Matlab,
            and wraps `standard_normal`. That function takes a
            tuple to specify the size of the output, which is consistent with
            other NumPy functions like `numpy.zeros` and `numpy.ones`.

        .. note::
            New code should use the ``standard_normal`` method of a ``default_rng()``
            instance instead; see `random-quick-start`.

        If positive int_like arguments are provided, `randn` generates an array
        of shape ``(d0, d1, ..., dn)``, filled
        with random floats sampled from a univariate "normal" (Gaussian)
        distribution of mean 0 and variance 1. A single float randomly sampled
        from the distribution is returned if no argument is provided.

        Parameters
        ----------
        d0, d1, ..., dn : int, optional
            The dimensions of the returned array, must be non-negative.
            If no argument is given a single Python float is returned.

        Returns
        -------
        Z : ndarray or float
            A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from
            the standard normal distribution, or a single such float if
            no parameters were supplied.
"""
pass



#### 4.2 np.random.common指定方差和期望

用于创建指定期望和方差正态分布数据的数组

函数定义

def normal(loc=0.0, scale=1.0, size=None): # real signature unknown; restored from doc

"""
normal(loc=0.0, scale=1.0, size=None)

        Draw random samples from a normal (Gaussian) distribution.

        The probability density function of the normal distribution, first
        derived by De Moivre and 200 years later by both Gauss and Laplace
        independently [2]_, is often called the bell curve because of
        its characteristic shape (see the example below).

        The normal distributions occurs often in nature.  For example, it
        describes the commonly occurring distribution of samples influenced
        by a large number of tiny, random disturbances, each with its own
        unique distribution [2]_.

        .. note::
            New code should use the ``normal`` method of a ``default_rng()``
            instance instead; see `random-quick-start`.

        Parameters
        ----------
        loc : float or array_like of floats
            Mean ("centre") of the distribution.
        scale : float or array_like of floats
            Standard deviation (spread or "width") of the distribution. Must be
            non-negative.
        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 ``loc`` and ``scale`` are both scalars.
            Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.

        Returns
        -------
        out : ndarray or scalar
            Drawn samples from the parameterized normal distribution.

        See Also
        --------
        scipy.stats.norm : probability density function, distribution or
            cumulative density function, etc.
        Generator.normal: which should be used for new code.

        Notes
        -----
        The probability density for the Gaussian distribution is

        .. math:: p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}
                         e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },

        where :math:`\mu` is the mean and :math:`\sigma` the standard
        deviation. The square of the standard deviation, :math:`\sigma^2`,
        is called the variance.

        The function has its peak at the mean, and its "spread" increases with
        the standard deviation (the function reaches 0.607 times its maximum at
        :math:`x + \sigma` and :math:`x - \sigma` [2]_).  This implies that
        normal is more likely to return samples lying close to the mean, rather
        than those far away.

        References
        ----------
        .. [1] Wikipedia, "Normal distribution",
               https://en.wikipedia.org/wiki/Normal_distribution
        .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
               Random Variables and Random Signal Principles", 4th ed., 2001,
               pp. 51, 51, 125.
"""
pass



示例代码:

import numpy as np

a1 = np.random.randn(2)
a2 = np.random.normal(0, 1, 2)
print(a1)
print(''~~'' * 10)
print(a2)
print(''--'' * 20)

b1 = np.random.randn(2, 3)
b2 = np.random.normal(0, 1, (2, 3))
print(b1)
print(''~~'' * 10)
print(b2)


运行结果:

[-0.08968467 0.19935229]

[-2.70345057  0.31810813]
----------------------------------------
[[ 0.26098236  0.59379753 -0.70686308]
 [-0.78541554 -0.27910239 -0.15193886]]

[[-0.92466689 0.580677 0.80772163]
[ 2.17103711 -0.11340317 -0.06021829]]


---
> 备注:   
> 更多精彩博客,请访问:[聂发俊的技术博客](http://www.niefajun.com/)  博客内容修改和更新,只更新个人博客。
> 对应视频教程,请访问:[python400](https://www.bilibili.com/video/BV1WE411j7p3)  
> 完整markdown笔记,请访问: [python400_learn_github](https://github.com/niefajun/python400_learn)

"import numpy as np" ImportError: No module named numpy

问题:没有安装 numpy

解决方法:

下载文件,安装

numpy-1.8.2-win32-superpack-python2.7

安装运行 import numpy,出现

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import numpy
  File "C:\Python27\lib\site-packages\numpy\__init__.py", line 153, in <module>
    from . import add_newdocs
  File "C:\Python27\lib\site-packages\numpy\add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "C:\Python27\lib\site-packages\numpy\lib\__init__.py", line 8, in <module>
    from .type_check import *
  File "C:\Python27\lib\site-packages\numpy\lib\type_check.py", line 11, in <module>
    import numpy.core.numeric as _nx
  File "C:\Python27\lib\site-packages\numpy\core\__init__.py", line 6, in <module>
    from . import multiarray
ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。

原因是:python 装的是 64 位的,numpy 装的是 32 位的

重新安装 numpy 为:numpy-1.8.0-win64-py2.7

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数

3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数

目录

[TOC]

前言

具体我们来学 Numpy 的统计函数

(一)函数一览表

调用方式:np.*

.sum(a) 对数组 a 求和
.mean(a) 求数学期望
.average(a) 求平均值
.std(a) 求标准差
.var(a) 求方差
.ptp(a) 求极差
.median(a) 求中值,即中位数
.min(a) 求最大值
.max(a) 求最小值
.argmin(a) 求最小值的下标,都处里为一维的下标
.argmax(a) 求最大值的下标,都处里为一维的下标
.unravel_index(index, shape) g 根据 shape, 由一维的下标生成多维的下标

(二)统计函数 1

(1)说明

(2)输出

.sum(a)

.mean(a)

.average(a)

.std(a)

.var(a)

(三)统计函数 2

(1)说明

(2)输出

.max(a) .min(a)

.ptp(a)

.median(a)

.argmin(a)

.argmax(a)

.unravel_index(index,shape)

作者:Mark

日期:2019/02/11 周一

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案

如何解决Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案?

希望有人能在这里提供帮助。我一直在绕圈子一段时间。我只是想设置一个 python 脚本,它将一些 json 数据从 REST API 加载到云数据库中。我在 Anaconda 上设置了一个虚拟环境(因为 GCP 库推荐这样做),安装了依赖项,现在我只是尝试导入库并向端点发送请求。 我使用 Conda(和 conda-forge)来设置环境并安装依赖项,所以希望一切都干净。我正在使用带有 Python 扩展的 VS 编辑器作为编辑器。 每当我尝试运行脚本时,我都会收到以下消息。我已经尝试了其他人在 Google/StackOverflow 上找到的所有解决方案,但没有一个有效。我通常使用 IDLE 或 Jupyter 进行脚本编写,没有任何问题,但我对 Anaconda、VS 或环境变量(似乎是相关的)没有太多经验。 在此先感谢您的帮助!

  \Traceback (most recent call last):
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 22,in <module>
from . import multiarray
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\multiarray.py",line 12,in <module>
from . import overrides
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\overrides.py",line 7,in <module>
from numpy.core._multiarray_umath import (
ImportError: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
File "c:\API\citi-bike.py",line 4,in <module>
import numpy as np
File "C:\Conda\envs\gcp\lib\site-packages\numpy\__init__.py",line 150,in <module>
from . import core
File "C:\Conda\envs\gcp\lib\site-packages\numpy\core\__init__.py",line 48,in <module>
raise ImportError(msg)
ImportError:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions Failed. This error can happen for
many reasons,often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

* The Python version is: python3.9 from "C:\Conda\envs\gcp\python.exe"
* The NumPy version is: "1.21.1"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: DLL load Failed while importing _multiarray_umath: The specified module Could not be found.

解决方法

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

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

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

Difference between import numpy and import numpy as np

Difference between import numpy and import numpy as np

Difference between import numpy and import numpy as np

up vote 18 down vote favorite

5

I understand that when possible one should use

import numpy as np

This helps keep away any conflict due to namespaces. But I have noticed that while the command below works

import numpy.f2py as myf2py

the following does not

import numpy as np
np.f2py #throws no module named f2py

Can someone please explain this?

python numpy

shareimprove this question

edited Mar 24 ''14 at 23:20

mu 無

24.7k104471

asked Mar 24 ''14 at 23:19

user1318806

3001311

 
1  

@roippi have you tried exit your python and enter it and just do import numpy then numpy.f2py ? It throws an error in my case too – aha Mar 24 ''14 at 23:24

1  

Importing a module doesn''t import sub-modules. You need to explicitly import the numpy.f2py module regardless of whether or not/how numpy itself has been imported. – alecb Mar 24 ''14 at 23:39

add a comment

4 Answers

active oldest votes

 

up vote 13 down vote

numpy is the top package name, and doing import numpy doesn''t import submodule numpy.f2py.

When you do import numpy it creats a link that points to numpy, but numpy is not further linked to f2py. The link is established when you do import numpy.f2py

In your above code:

import numpy as np # np is an alias pointing to numpy, but at this point numpy is not linked to numpy.f2py
import numpy.f2py as myf2py # this command makes numpy link to numpy.f2py. myf2py is another alias pointing to numpy.f2py as well

Here is the difference between import numpy.f2py and import numpy.f2py as myf2py:

  • import numpy.f2py
    • put numpy into local symbol table(pointing to numpy), and numpy is linked to numpy.f2py
    • both numpy and numpy.f2py are accessible
  • import numpy.f2py as myf2py
    • put my2py into local symbol table(pointing to numpy.f2py)
    • Its parent numpy is not added into local symbol table. Therefore you can not access numpy directly

shareimprove this answer

edited Mar 25 ''14 at 0:31

answered Mar 24 ''14 at 23:33

aha

1,2291718

 

add a comment

 

up vote 7 down vote

The import as syntax was introduced in PEP 221 and is well documented there.

When you import a module via

import numpy

the numpy package is bound to the local variable numpy. The import as syntax simply allows you to bind the import to the local variable name of your choice (usually to avoid name collisions, shorten verbose module names, or standardize access to modules with compatible APIs).

Thus,

import numpy as np

is equivalent to,

import numpy
np = numpy
del numpy

When trying to understand this mechanism, it''s worth remembering that import numpy actually means import numpy as numpy.

When importing a submodule, you must refer to the full parent module name, since the importing mechanics happen at a higher level than the local variable scope. i.e.

import numpy as np
import numpy.f2py   # OK
import np.f2py      # ImportError

I also take issue with your assertion that "where possible one should [import numpy as np]". This is done for historical reasons, mostly because people get tired very quickly of prefixing every operation with numpy. It has never prevented a name collision for me (laziness of programmers actually suggests there''s a higher probability of causing a collision with np)

Finally, to round out my exposé, here are 2 interesting uses of the import as mechanism that you should be aware of:

1. long subimports

import scipy.ndimage.interpolation as warp
warp.affine_transform(I, ...)

2. compatible APIs

try:
    import pyfftw.interfaces.numpy_fft as fft
except:
    import numpy.fft as fft
# call fft.ifft(If) with fftw or the numpy fallback under a common name

shareimprove this answer

answered Mar 25 ''14 at 0:59

hbristow

68345

 

add a comment

 

up vote 1 down vote

numpy.f2py is actually a submodule of numpy, and therefore has to be imported separately from numpy. As aha said before:

When you do import numpy it creats a link that points to numpy, but numpy is not further linked to f2py. The link is established when you do import numpy.f2py

when you call the statement import numpy as np, you are shortening the phrase "numpy" to "np" to make your code easier to read. It also helps to avoid namespace issues. (tkinter and ttk are a good example of what can happen when you do have that issue. The UIs look extremely different.)

shareimprove this answer

answered Mar 24 ''14 at 23:47

bspymaster

760923

 

add a comment

 

up vote 1 down vote

This is a language feature. f2py is a subpackage of the module numpy and must be loaded separately.

This feature allows:

  • you to load from numpy only the packages you need, speeding up execution.
  • the developers of f2py to have namespace separation from the developers of another subpackage.

Notice however that import numpy.f2py or its variant import numpy.f2py as myf2py are still loading the parent module numpy.

Said that, when you run

import numpy as np
np.f2py

You receive an AttributeError because f2py is not an attribute of numpy, because the __init__() of the package numpy did not declare in its scope anything about the subpackage f2py.

shareimprove this answer

answered Mar 24 ''14 at 23:57

gg349

7,67321739

 
    

when you do import numpy.f2py as myf2py, how do you access its parent numpy? it seems import numpy.f2py allows you to access its parent numpy, but import numpy.f2py as myf2py doesn''t – aha Mar 25 ''14 at 0:00

    

You don''t access it because you decided you didn''t want to use anything from numpy, and you only care of using the subpackage. It is similar to using from foo import bar: the name foo will not be accessible. See the comment after the first example of the docs, LINK – gg349 Mar 25 ''14 at 0:05

add a comment

今天关于python-numpy-03-创建特定形式数组numpy中创建特定数组的方法的分享就到这里,希望大家有所收获,若想了解更多关于"import numpy as np" ImportError: No module named numpy、3.7Python 数据处理篇之 Numpy 系列 (七)---Numpy 的统计函数、Anaconda Numpy 错误“Importing the Numpy C Extension Failed”是否有另一种解决方案、Difference between import numpy and import numpy as np等相关知识,可以在本站进行查询。

本文标签: