- Numerical Python,数值的Python,补充了Python语言所欠缺的数值计算能力
- Numpy 是其他数据分析及机器学习库的底层库
- Numpy 完全标准C语言实现,运行效率充分优化
- Numpy 完全开源免费
简单来说,就是补齐了Python的计算短板,效率高,还免费。
非常简单,直接pip就行
pip install numpy
如果觉得官方源慢,可以使用清华的源
https://mirrors.tuna.tsinghua.edu.cn/help/pypi/
import numpy as np # 直接import即可
'''
测试:ndarray
'''
import numpy as np
lst = [1, 2, 3, 4, 5, 6]
ary = np.array([1, 2, 3, 4, 5, 6])
print(ary[1])
print(ary[1:3])
for i in ary:
print(i)
print(lst, type(lst))
print(ary, type(ary))
'''
2
[2 3]
1
2
3
4
5
6
[1, 2, 3, 4, 5, 6]
[1 2 3 4 5 6]
ndarray和列表一样,可以通过数字索引访问,可以切片,也可以通过for遍历
乍一看感觉和列表除了类型不同也没什么区别,但是用起来就不一样了
先来做个最简单的测试
'''
# test1
print('', 'test1'.center(50, '-'), '', sep='\n')
print(lst * 2)
print(ary * 2)
'''
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
[ 2 4 6 8 10 12]
list * 2 会在原有list后拼接一个一模一样的list,
而ndarray * 2 则会将它的每一项分别 *2
我们知道,两个列表是不可以相乘的
那将两个ndarray能否相乘呢?
'''
# test2
print('', 'test2'.center(50, '-'), '', sep='\n')
print(ary * ary)
'''
[ 1 4 9 16 25 36]
可以看到,两个ndarray相乘是将对应位置的数分别相乘
那如果两个ndarray长度不一样呢?
'''
# test3
print('', 'test3'.center(50, '-'), '', sep='\n')
try:
ary2 = np.array([1, 2, 3, 4, 5])
print(ary * ary2)
except Exception as e:
print(e.__class__.__name__+':',e)
'''
ValueError: operands could not be broadcast together with shapes (6,) (5,)
可以看到,报错了,说明ndarray一定要长度相等才可以相乘
'''
这一篇就讲到这,ndarray还是有不少要注意的地方
个人工作室: Sakuyark
网站:sakuyark.com