Python-numpy

numpy 基础

import numpy as np
arr = np.array([1, 3, 5, 'a'])
arr #打印
arr_z = np.zeros(10)
arr_z = np.zeros((2, 3))#元组-不可变
arr_o = np.ones(10)
arr.shape#打印结构
arr.size#打印元素个数
type(arr)#打印数组类型
arr.ndim#打印维数
arr5 = np.full((2, 3),np.pi)#填充
line = np.linspace(0, 15, 30, endpoint = False)
#0-15间等差产生30个数(endpoint为bool值指定是否包含结束点)
line

函数默认带参:

  • 默认值声明从右向左,参数分配默认从左向右
  • 遇到有些有默认有些无默认,需要将有默认的放在右侧
  • 还可以通过调用时指定参数的对应名,指定参数
def func(name = "sylvia",age = "12"):
    print("test "+ age)
    if int(age) > 20:
        return name + " adults"
    else:
        return name + " youth"
print(func(age = "15"))

匿名函数:

a = lambda x : x + 1
a(1)
arr = np.fromfunction(lambda x : x + 2, (10, ))#操作、10个元素
arr
arr = np.fromfunction(lambda x,y : (x + 2)*(y + 1), (10, 2))
#生成一个二维数表
arr
arr = np.random.randint(1, 10, (2, 3))#产生整数随机数:1-10之间的(2,3)数组
arr = np.array([1, 2, 'a'])
arr.dtype

数组操作

arr = np.arange(0, 10, 0.1)
arr
arr[2 : 3]
arr[[2, 3, 4]] = 5#批量赋值
arr = np.arange(12).reshape(3, 4)
arr
arr[0:2]
arr[0:2, 0:2]
names = np.array(["zhao","qian","sun","li","zhou"])
"wang" in names
names == "wang"
#输出:array([False, False, False, False, False])
arr = np.arange(10)
arr[arr>4]#代替遍历
data = np.random.randn(4, 2)
np.sum(data, axis=1)#逐行求和
np.sum(data, axis=0)#逐列求和
arr = np.random.randint(0,101,(4,5))
arrMax = np.max(arr, axis=0)
arrMin = np.min(arr, axis=0)
arrPass = arr[arr>60]
arr
arr[1,1:3]
display(arrMin,arrMax)

你可能感兴趣的:(Python-numpy)