ndarray的用法总结
#发现ndarray的一维,二维都可以用[i][j], 它们都是下标索引的连用, 比如j表示第j个元素;
#二维ndarray可以用[m, n]来进行行列的操作,类似matlab中的用法.取某一列是[:, n],而不是[:][n],后者只是取第n个元素,因为[:]表示创建一个副本.
import numpy as np array1 = np.array([[1,2,3], [4,5,6]]) #二维数组, (2,3) print(array1) fields = ["a", "b", "c"] dtype = np.dtype([("a", int), ("b", np.float64), ("c", np.float64)]) ndarray1 = np.empty(shape=(2, ), dtype=dtype) #一维数组, (2, ) for i in range(len(array1)): for j, field in enumerate(fields): #绑定下标和数据,下标从0开始 ndarray1[field][i] = array1[i][j] #dtype和列名关联后可以通过[dtype的列名][行序号]来访问,也可以用[行序号][元组中位置序号]
#ndarray1[i][j] = array1[i][j] print(ndarray1)
print(ndarray1[0][1]) print(ndarray1["b"][0]) ndarray2 = np.empty(shape=(2,3), dtype=np.float64) #二维数组, (2, 3) for i in range(len(array1)): for j in range(len(array1[0])): ndarray2[i][j] = array1[i][j] print(ndarray2)
[[1 2 3] [4 5 6]]
[(1, 2., 3.) (4, 5., 6.)]
2.0 2.0
[[1. 2. 3.] [4. 5. 6.]]
新战场:https://blog.csdn.net/Stephen___Qin