numpy 数组的相关操作例题
# 生成一维数组、二维数组并查看shape # 一维数组 a1: [1 2 'a' 'hello' [1, 2, 3] {'two':200,'one':100}] import numpy as np a1=np.array([1, 2, 'a', 'hello', [1, 2, 3], {'two':200,'one':100}]) print(a1) # a1的shape print("a1.shape: ",a1.shape,"na1.shape[0]: ",a1.shape[0]) # "na1.shape[1]: ",a1.shape[1] # 二维数组 a2: # [['0' '1' '2' '3' '4' '5'] # ['a' 'b' 'c' 'd' 'e' 'f'] # ['True' 'False' 'True' 'False' 'True' 'True']] a2=np.array([['0' '1' '2' '3' '4' '5'],['a' 'b' 'c' 'd' 'e' 'f'],['True' 'False' 'True' 'False' 'True' 'True']]) print(a2) # a2的shape print("行值为:",a2.shape[0],"n列值为:",a2.shape[1])
若输出a1.shape[1]会提示越界因为a1为一维数组
# 生成一个一维数组,起始值为5,终点值为15,样本值为10 import numpy as np a=np.arange(5,15) print(a)
a的最终输出结果为:[ 5 6 7 8 9 10 11 12 13 14] ,仅到14
# 按照要求创建以下数组 # [[0. 0. 0. 0.] # [0. 0. 0. 0.] # [0. 0. 0. 0.] # [0. 0. 0. 0.]] # ------------------- import numpy as np a=np.zeros([4,4]) print(a) # [[1. 1. 1.] # [1. 1. 1.]] # ------------------- b=np.ones([2,3]) print(b) # [[1 0 0] # [0 1 0] # [0 0 1]] d=np.identity(3,dtype=int) print(d)
# 创建一个20个元素的数组,分别改变成两个形状:(4,5),(5,6) # [[ 0 1 2 3 4] eprogram# 生成一维数组、二维数组并查看shape.py' # [ 5 6 7 8 9] # [10 11 12 13 14] # [15 16 17 18 19]] # ----------------- # [[ 0 1 2 3 4 5] # [ 6 7 8 9 10 11] # [12 13 14 15 16 17] # [18 19 0 1 2 3] # [ 4 5 6 7 8 9]] import numpy as np a=np.arange(20).reshape(4,5) b=np.resize(np.arange(20),(5,6)) print(a) print("-----------------") print(b)
numpy.resize(a, shape)返回具有指定形状的新数组。对于元素不足的情况重复填写原数组元素
# 创建一个(4,4)的数组,把其元素类型改为字符型 # [['0' '1' '2' '3'] # ['4' '5' '6' '7'] # ['8' '9' '10' '11'] # ['12' '13' '14' '15']] import numpy as np a=np.resize(np.arange(16),(4,4)).astype(str) print(a)
numpy.astype用于转换数据类型,python字符串类型为:str
# 运用数组的运算方法得到结果: result=ar*10+100,并求出result的均值及求和 # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # [12 13 14 15]] # --------------- # [[100 110 120 130] # [140 150 160 170] # [180 190 200 210] # [220 230 240 250]] import numpy as np ar=np.arange(16).reshape((4,4)) result=ar*10+100 print(ar) print("---------------") print(result) print(sum(sum(result))/result.size) # 均值 print(sum(sum(result))) # 求和
由于数组result为二维数组,所以sum(result)是对result的每行分别进行求和运算,结果为 [640 680 720 760],len(result)的结果为4,表示的是result数组的行数。所以用sum(sum(result))两次求和,result.size获取元素个数
numpy数组最大的特点是任何运算都会自动的对数组当中的所有变量进行运算
# 创建起始值为0长度为10的数组,筛选出元素值大于5的值并生成新的数组 # [[0 1 2 3 4] # [5 6 7 8 9]] import numpy as np a=np.arange(10).reshape(2,5) b=a[a>5] print(b)
numpy.where[条件] 输出的是符合条件的元素位置,若想使用numpy.where方法,则将a[a>5]替换为a[np.where(a>5)]
# 创建包含10个元素的正太分布的一维数组 import numpy as np a=np.random.randn(10) print(a)
# 创建10*10的整数随机数组,取值范围0-100 import numpy as np a=np.random.randint(100,size=(10,10)) print(a)