#创建一维数组
import numpy as np
a = np.array([1,2,3])
print(a)
[1 2 3]
#创建二维数组
a = np.array([[1,2],[3,4]])
print(a)
[[1 2]
[3 4]]
#设置数组的最小维度
import numpy as np
a = np.array([1,2,3,4,5],ndmin = 2)
print(a)
[[1 2 3 4 5]]
#使用dtype参数设置数组类型为复数
import numpy as np
a = np.array([1,2,3],dtype = np.complex)
print(a)
[1.+0.j 2.+0.j 3.+0.j]
#使用dtype对象设置数据类型
import numpy as np
x=np.array(5,dtype="float32")
print('x为:',x)
print('x对象的data属性:',x.data)
print('x对象的size属性:',x.size)
print('x对象的维数:',x.ndim)
y=np.array(x,dtype = "bool_")
print('转换为bool类型的x为:',y)
z=np.array(y,dtype = "float16")
print('True值转换为float16类型为:',z)
x为: 5.0
x对象的data属性: <memory at 0x0000021F811CF360>
x对象的size属性: 1
x对象的维数: 0
转换为bool类型的x为: True
True值转换为float16类型为: 1.0
#使用astype()转换数据类型
import numpy as np
a = np.int32(5000)
print(a)
a = a.astype("float32")
print(a)
b = np.array([1,2,3],dtype = "int32")
print(b)
b = b.astype("float64")
print(b)
5000
5000.0
[1 2 3]
[1. 2. 3.]
#使用嵌套for循环对ndarray数组进行迭代遍历
import numpy as np
a = np.arange(0,60,5)
a = a.reshape(3,4)
for xline in a:
for yitem in xline:
print(yitem,end = ' ')
0 5 10 15 20 25 30 35 40 45 50 55
#ndarray的统计计算
import numpy as np
stus_score = np.array([[80,88],[82,81],[84,75],[86,83],[75,81]])
#求每列的最大值(0表示列)
result = np.max(stus_score, axis = 0)
print(result)
#求每行的最大值(1表示行)
result = np.max(stus_score, axis = 1)
print(result)
#求每列的平均值(0表示列)
result = np.mean(stus_score, axis = 0)
print(result)
[86 88]
[88 82 84 86 81]
[81.4 81.6]