numpy的核心数据类型:ndarry数组
import numpy as np
lst = [1, 2, 3, 4, 5]
ary = np.array([1, 2, 3, 4, 5])
print(ary[1])
print(ary[1:3])
for i in ary:
print(i)
输出:
2
[2 3]
1
2
3
4
5
print(lst, type(lst))
print(ary, type(ary))
输出:
[1, 2, 3, 4, 5] <class 'list'>
[1 2 3 4 5] <class 'numpy.ndarray'>
ndarray和列表一样,可以通过数字索引访问,可以切片,也可以通过for遍历,但是在一些使用方法上与列表有所不同。
示例
print(lst * 2)
print(ary * 2)
输出:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
[ 2 4 6 8 10]
list * 2 会在原有list后拼接一个一模一样的list,而ndarray * 2 则会将它的每一项分别 *2。
当两个ndarray相乘是将对应位置的数分别相乘:
print(ary * ary)
输出:
[ 1 4 9 16 25]
如果两个ndarray长度不一样进行相乘时:
try:
ary2 = np.array([1, 2, 3, 4])
print(ary * ary2)
except Exception as e:
print(e.__class__.__name__+':',e)
输出:
ValueError: operands could not be broadcast together with shapes (5,) (4,)
可以看到,报错了,说明ndarray一定要长度相等才可以相乘。