Numpy——进阶篇

impoort numpy as np

arr=np.arange(10)

#输出奇数
arr[arr%2==1]

#将arr中的所有奇数替换为-1,而不改变arr
out=np.where(arr%2==1,-1,arr)

a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)

#垂直叠加两个数组
np.vstack([a,b])
#np.concatenate([a,b],axis=0)
#np.r_[a, b]

#水平叠加两个数组
np.hstack([a,b])
#np.concatenate([a,b],axis=1)
#np.c_[a, b]

#获取数组a和数组b之间的公共项。
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
c = np.intersect1d(a,b)

#从数组a中删除数组b中的所有项。
a = np.array([1,2,3,4,5])
b = np.array([4,5,6,4,5,9])
d = np.setdiff1d(a,b)

#获取a和b元素匹配的位置,不仅元素相同需在位置上也相同
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
p = np.where(a==b)

#获取5到10之间的所有项目。
a=np.arange(14)
a[(a>=5)&(a=<10)]
#index = np.where((a >= 5) & (a <= 10))
#a[index]

#转换适用于两个标量的函数maxx,以处理两个数组。
#np.vectorize将函数向量化。
def maxx(x, y):
    """Get the maximum of two items"""
    if x >= y:
        return x
    else:
        return y

pair_max = np.vectorize(maxx, otypes=[float])

a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])

print(pair_max(a, b))
print(pair_max.__doc__)

#今天做到15题—今天长大了一岁,希望以后的日子能够舒心,更有动力!

猜你喜欢

转载自www.cnblogs.com/DHuifang004/p/11042546.html