- 修改(对象的副本或视图)
import numpy as np a = np.arange(16).reshape((4, 4)) # 赋值(与列表相同,都是指向同一内存地址,当其中一个元素发生改变时,另外一个也改变) b = a # 赋值(这里相当于列表的深度拷贝,内存地址不同) c = a.copy() # 这时经过切分,内存地址也不同,当a或b发生改变时,c不会发生改变 d = a[[1,2],] b[1][1] = 111 #这里改变时,a里的元素也发生改变
- 向量化(其实就是使代码更简洁,可读性更强,使代码更贴近于数学运算,如求a*b 使用for循环)
import numpy as np a = np.arange(16).reshape((4, 4)) b = np.arange(16).reshape((4, 4)) c = np.zeros((4,4)) rows = a.shape[0] columns = a.shape[1] for i in range(rows): for j in range(columns): c[i][j] = a[i][j] * b[i][j] print(c)
- 结构化(结构化就是在数据里使用多种类型,相似于c语言中的结构体)
import numpy as np """ 元素类型简写 bytes b1 int i1,i2,i4,i8 unsigned ints u1,u2,u4,u8 floats f2,f4,f8 comples c8,c16 fixed length strings a<n> """ # a 与 b 其实相同,只是一个用简写说明,另外一用具体类型说明。 a = np.array([(1, 'xiaohong', 88.5, 2 - 2j), (2, 'xiaoming', 81.5, 1 + 2j), (1, 'xiaoshan', 67, 1 + 2j)], dtype=('i2,a8,f4,c8')) b = np.array([(1, 'xiaohong', 88.5, 2 - 2j), (2, 'xiaoming', 81.5, 1 + 2j), (1, 'xiaoshan', 67, 1 + 2j)], dtype=('int16,a8,float16,complex64')) print(a.dtype) # [('f0', '<i2'), ('f1', 'S8'), ('f2', '<f4'), ('f3', '<c8')] # 查找第二个列 print(a[1]) # (2, b'xiaoming', 81.5, 1.+2.j) # 根据名字查找 print(a['f1']) # [b'xiaohong' b'xiaoming' b'xiaoshan'] # 使用自定义名字。 c = np.array([(1, 'xiaohong', 88.5, 2 - 2j), (2, 'xiaoming', 81.5, 1 + 2j), (1, 'xiaoshan', 67, 1 + 2j)], dtype=[("id", 'i2'), ('name', 'a8'), ('score', 'f4'), ('complex', 'c8')]) # 根据名字查找 print(c['name']) # [b'xiaohong' b'xiaoming' b'xiaoshan'] # 修改名字 a.dtype.names = ('id', 'name', 'score', 'complex') print(a['score']) # [88.5 81.5 67. ]
python numpy随笔(数组的修改、向量化、结构化)
猜你喜欢
转载自blog.csdn.net/fm345689/article/details/88631043
今日推荐
周排行