标签:操作 方便 bsp sha 风格 基本数据 列表 for src
为什么要学NumPy
NumPy的优势
ndarray与Python原生list运算效率对比
import random
import time
import numpy as np
a = []
for i in range(100000000):
a.append(random.random())
t1 = time.time()
sum1=sum(a)
t2=time.time()
b=np.array(a)
t4=time.time()
sum3=np.sum(b)
t5=time.time()
print(t2-t1, t5-t4)
输出:
8.297281980514526 1.7647507190704346
创建一维数组
import numpy as np list1 = [1,2,3,4] oneArray = np.array(list1) print(type(oneArray)) print(oneArray) 输出: <class ‘numpy.ndarray‘> [1 2 3 4]
import numpy as np
# 创建数组的多种形式
# 1. 直接传入列表的方式
t1 = np.array([1,2,3])
print(t1)
print(type(t1))
# 2. 传入range生成序列
t2 = np.array(range(10))
print(t2)
print(type(t2))
# 3. 使用numpy自带的np.arange()生成数组
t3 = np.arange(0,10,2)
print(t3)
print(type(t3))
输出:
[1 2 3]
<class ‘numpy.ndarray‘>
[0 1 2 3 4 5 6 7 8 9]
<class ‘numpy.ndarray‘>
[0 2 4 6 8]
<class ‘numpy.ndarray‘>
创建二位数组
import numpy as np
list2 = [[1,2],[3,4],[5,6]]
twoArray = np.array(list2)
print(twoArray)
#返回数组类型
print(twoArray.ndim)
#返回数组形状
print(twoArray.shape)
#返回数组的元素个数
print(twoArray.size)
输出:
[[1 2]
[3 4]
[5 6]]
2
(3, 2)
6
调整数组形状
#二维变三维
import numpy as np
four = np.array([[1,2,3],[4,5,6]])
# 修改的是原有的
four.shape = (3,2)
print(four)
print("-"*20)
# 返回一个新的数组
five = four.reshape(3,2)
print(five)
输出:
[[1 2]
[3 4]
[5 6]]
--------------------
[[1 2]
[3 4]
[5 6]]
#多维变一维
import numpy as np
four = np.array([[1,2,3],[4,5,6]])
# 将多维变成一维数组
five = four.reshape((6,),order=‘F‘)
# 默认情况下‘C’以行为主的顺序展开,‘F’(Fortran风格)意味着以列的顺序展开
six = four.flatten(order=‘F‘)
print(five)
print(six)
输出:
[1 4 2 5 3 6]
[1 4 2 5 3 6]
数组转换为list
import numpy as np a= np.array([9, 12, 88, 14, 25]) list_a = a.tolist() print(list_a) print(type(list_a)) 输出: [9, 12, 88, 14, 25] <class ‘list‘>
NumPy的数据类型
import numpy as np
import random
f = np.array([1,2,3,4,5], dtype = np.int16)
# 返回数组中每个元素的字节单位长度
print(f.itemsize)
# 获取数据类型
print(f.dtype)
# 调整数据类型
f1 = f.astype(np.int64)
print(f1.dtype)
# 拓展随机生成小数
# 使用python语法,保留两位
print(round(random.random(),2))
arr = np.array([random.random() for i in range(10)]) # 取小数点后两位
print(np.round(arr,2))
输出:
2
int16
int64
0.02
[0.72 0.02 0.93 0.99 0.12 0.16 0.19 0.25 0.89 0. ]
数组的计算
import numpy as np
import random
t1 = np.arange(24).reshape((6,4))
print(t1)
print("-"*20)
print(t1+2)
print("-"*20)
print(t1*2)
print("-"*20)
print(t1/2)
输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]
--------------------
[[ 2 3 4 5]
[ 6 7 8 9]
[10 11 12 13]
[14 15 16 17]
[18 19 20 21]
[22 23 24 25]]
--------------------
[[ 0 2 4 6]
[ 8 10 12 14]
[16 18 20 22]
[24 26 28 30]
[32 34 36 38]
[40 42 44 46]]
--------------------
[[ 0. 0.5 1. 1.5]
[ 2. 2.5 3. 3.5]
[ 4. 4.5 5. 5.5]
[ 6. 6.5 7. 7.5]
[ 8. 8.5 9. 9.5]
[10. 10.5 11. 11.5]]
标签:操作 方便 bsp sha 风格 基本数据 列表 for src
原文地址:https://www.cnblogs.com/imcati/p/11258966.html