GVKun编程网logo

NumPy(数组计算)(NumPy数组计算基础教室评语)

1

对于想了解NumPy(数组计算)的读者,本文将是一篇不可错过的文章,我们将详细介绍NumPy数组计算基础教室评语,并且为您提供关于"importnumpyasnp"ImportError:Nomodu

对于想了解NumPy(数组计算)的读者,本文将是一篇不可错过的文章,我们将详细介绍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的有价值信息。

本文目录一览:

NumPy(数组计算)(NumPy数组计算基础教室评语)

NumPy(数组计算)(NumPy数组计算基础教室评语)

一、介绍

  NumPy是高性能科学计算和数据分析的基础包。它是pandas等其他各种工具的基础。

1.主要功能

1)ndarray,一个多维数组结构,高效且节省空间
2)无需循环对整组数据进行快速运算的数学函数
3)读写磁盘数据的工具以及用于操作内存映射文件的工具
4)线性代数、随机数生成和傅里叶变换功能
5)用于集成C、C++等代码的工具

2.安装方法

pip install numpy

3.引用方法

import numpy as np  

二、ndarray-多维数组对象 

创建ndarray:np.array()
ndarray是多维数组结构,与列表的区别是:
数组对象内的元素类型必须相同
数组大小不可修改
常用属性:
T		数组的转置(对高维数组而言)
dtype	数组元素的数据类型
size	数组元素的个数
ndim	数组的维数
shape	数组的维度大小(以元组形式) 

三、ndarray-数据类型

ndarray数据类型:dtype:
布尔型:bool_
整型:int_ int8 int16 int32 int64
无符号整型:uint8 uint16 uint32 uint64
浮点型:float_ float16 float32 float64
复数型:complex_ complex64 complex128

四、ndarray-创建

array()        将列表转换为数组,可选择显式指定dtype
arange()        range的numpy版,支持浮点数
linspace()    类似arange(),第三个参数为数组长度
zeros()        根据指定形状和dtype创建全0数组
ones()        根据指定形状和dtype创建全1数组
empty()        根据指定形状和dtype创建空数组(随机值)
eye()        根据指定边长和dtype创建单位矩阵

五、索引和切片

数组和标量之间的运算
a+1    a*3    1//a    a**0.5
同样大小数组之间的运算
a+b    a/b    a**b
数组的索引:
一维数组:a[5]
多维数组:
列表式写法:a[2][3]
新式写法:a[2,3] (推荐)
数组的切片:
一维数组:a[5:8]    a[4:]        a[2:10] = 1
多维数组:a[1:2, 3:4]    a[:,3:5]        a[:,1]
与列表不同,数组切片时并不会自动复制,在切片数组上的修改会影响原数组。    【解决方法:copy()】

六、布尔型索引

问题:给一个数组,选出数组中所有大于5的数。
  答案:a[a>5]
  原理:
    a>5会对a中的每一个元素进行判断,返回一个布尔数组
    布尔型索引:将同样大小的布尔数组传进索引,会返回一个由所有True对应位置的元素的数组

问题2:给一个数组,选出数组中所有大于5的偶数。
问题3:给一个数组,选出数组中所有大于5的数和偶数。
  答案:
     a[(a>5) & (a%2==0)]
     a[(a>5) | (a%2==0)]

 

import numpy as np
a = np.array([1,2,3,4,5,4,7,8,9,10])
a[a>5&(a%2==0)]  #注意加括号,不叫括号错误,如下
输出:array([ 1,  2,  3,  4,  5,  4,  7,  8,  9, 10])
a[(a>5)&(a%2==0)]
输出:array([ 8, 10])

七、花式索引

问题1:对于一个数组,选出其第1,3,4,6,7个元素,组成新的二维数组。
答案:a[[1,3,4,6,7]]

问题2:对一个二维数组,选出其第一列和第三列,组成新的二维数组。
答案:a[:,[1,3]]

八、通用函数

通用函数:能同时对数组中所有元素进行运算的函数

常见通用函数:

一元函数:abs, sqrt, exp, log, ceil, floor, rint, trunc, modf, isnan, isinf, cos, sin, tan

numpy.sqrt(array)                   平方根函数   
numpy.exp(array)                    e^array[i]的数组
numpy.abs/fabs(array)               计算绝对值
numpy.square(array)                 计算各元素的平方 等于array**2
numpy.log/log10/log2(array)         计算各元素的各种对数
numpy.sign(array)                   计算各元素正负号
numpy.isnan(array)                  计算各元素是否为NaN
numpy.isinf(array)                  计算各元素是否为NaN
numpy.cos/cosh/sin/sinh/tan/tanh(array) 三角函数
numpy.modf(array)                   将array中值得整数和小数分离,作两个数组返回
numpy.ceil(array)                   向上取整,也就是取比这个数大的整数 
numpy.floor(array)                  向下取整,也就是取比这个数小的整数
numpy.rint(array)                   四舍五入
numpy.trunc(array)                  向0取整 
numpy.cos(array)                       正弦值
numpy.sin(array)                    余弦值 
numpy.tan(array)                    正切值

二元函数:add, substract, multiply, divide, power, mod,  maximum, mininum, 

numpy.add(array1,array2)            元素级加法
numpy.subtract(array1,array2)       元素级减法
numpy.multiply(array1,array2)       元素级乘法
numpy.divide(array1,array2)         元素级除法 array1./array2
numpy.power(array1,array2)          元素级指数 array1.^array2
numpy.maximum/minimum(array1,aray2) 元素级最大值
numpy.fmax/fmin(array1,array2)      元素级最大值,忽略NaN
numpy.mod(array1,array2)            元素级求模
numpy.copysign(array1,array2)       将第二个数组中值得符号复制给第一个数组中值
numpy.greater/greater_equal/less/less_equal/equal/not_equal (array1,array2)
元素级比较运算,产生布尔数组
numpy.logical_end/logical_or/logic_xor(array1,array2)元素级的真值逻辑运算

九、补充知识:浮点数特殊值

1.浮点数:float
      浮点数有两个特殊值:

  • nan(Not a Number):不等于任何浮点数(nan != nan)
  • inf(infinity):比任何浮点数都大

在数据分析中,nan常被表示为数据缺失值

2.NumPy中创建特殊值:np.nan np.inf

3.在数据分析中,nan常被用作表示数据缺失值

既然nan连自己都不相等,那么怎么判断是不是NAN呢?
用a==a 只要返回False就能判断

十、数学和统计方法

常用函数:

sum	求和
cumsum 求前缀和
mean	求平均数
std	求标准差
var	求方差
min	求最小值
max	求最大值
argmin	求最小值索引
argmax	求最大值索引  

十一、随机数生成

随机数生成函数在np.random子包内
常用函数

rand	给定形状产生随机数组(0到1之间的数)
randint	给定形状产生随机整数
choice	给定形状产生随机选择
shuffle	与random.shuffle相同
uniform	给定形状产生随机数组

"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

我们今天的关于NumPy(数组计算)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的相关信息,可以在本站进行搜索。

本文标签: