In [1]:
import numpy as np
In [2]:
# 定义一个Python函数
def pyFunc(a):
result = np.zeros_like(a)
# 这里可以看出来对逐个元素的操作
result = 42
return result
使用zeros_like函数创建一个和a形状相同的、元素全部为0的数组result。flat属性提供了一个扁平迭代器,可以逐个设置数组元素的值。
使用frompyfunc创建通用函数,制定输入参数为1,输出参数为1。
In [3]:
ufunc1 = np.frompyfunc(pyFunc, 1, 1)
ret = ufunc1(np.arange(4))
print "The answer:\n", ret
In [4]:
ret = ufunc1(np.arange(4).reshape(2,2))
print "The answer:\n", ret
使用在第五节介绍的vectorize函数
In [5]:
func2 = np.vectorize(pyFunc)
ret = func2(np.arange(4))
print "The answer:\n", ret
In [6]:
a = np.arange(9)
print "a:\n", a
print "Reduce:\n", np.add.reduce(a)
In [7]:
print "Accumulate:\n", np.add.accumulate(a)
In [8]:
print "cumsum:\n", np.cumsum(a)
In [9]:
print "Reduceat:\n", np.add.reduceat(a, [0,5,2,7])
In [10]:
print "Reduceat step 1:", np.add.reduce(a[0:5])
print "Reduceat step 2:", a[5]
print "Reduceat step 3:", np.add.reduce(a[2:7])
print "Reduceat step 4:", np.add.reduce(a[7:])
In [11]:
print "Outer:\n", np.add.outer(np.arange(3), a)
在NumPy中,计算算术运算符+、-、* 隐式关联着通用函数add、subtrack和multiply。也就是说,当你对NumPy数组使用这些运算符时,对应的通用函数将自动被调用。
除法包含的过程比较复杂,在数组的除法运算中射击三个通用函数divide、true_divide和floor_division,以及两个对应的运算符/和//。
In [12]:
a = np.array([2, 6, 5])
b = np.array([1, 2, 3])
print "Divide:\n", np.divide(a, b), np.divide(b, a)
运算结果的小数部分被截断了
In [13]:
c = np.array([2.1, 6.2, 5.0])
d = np.array([1, 2, 1.9])
print "Divide:\n", np.divide(c, d), np.divide(d, c)
divide函数如果有一方是浮点数,那么结果也是浮点数结果
In [14]:
print "True Divide:\n", np.true_divide(a, b), np.true_divide(b, a)
In [15]:
print "Floor Divide:\n", np.floor_divide(a, b), np.floor_divide(b, a)
默认情况下,使用/运算符相当于调用divide函数,使用//运算符对应于floor_divide函数
In [16]:
a = np.arange(-4,4)
print "a:\n", a
print "Remainder:\n", np.remainder(a, 2)
mod函数与remainder函数的功能完全一致,%操作符仅仅是remainder函数的简写
In [17]:
print "Fmod:\n", np.fmod(a, 2)
In [18]:
print np.fmod(a, -2)
In [19]:
x = np.arange(-9, 9)
y = -x
print "Sign different? ", (x^y) < 0
print "Sign different? ", np.less(np.bitwise_xor(x, y), 0)
除了等于0的情况,所有整数对的符号都不一样。
In [20]:
b = np.arange(20)
print b
print "Power of 2 ?\n", (b & (b-1)) == 0
print "Power of 2 ?\n", np.equal(np.bitwise_and(b, (b-1)), 0)
In [21]:
print "Modulus 4:\n", x & ((1<<2) - 1)
In [25]:
def mod_2_pow(x, n):
mod = x & ((1<<n) - 1)
return mod
In [26]:
mod_2_pow(x,2)
Out[26]:
In [27]:
mod_2_pow(x, 3)
Out[27]: