# If a 1d array is added to a 2d array (or the other way), NumPy # chooses the array with smaller dimension and adds it to the one # with bigger dimension a = np.array([1, 2, 3]) b = np.array([(1, 2, 3), (4, 5, 6)]) print(np.add(a, b)) >>> [[2 4 6] [5 7 9]]
# Example of np.roots # Consider a polynomial function (x-1)^2 = x^2 - 2*x + 1 # Whose roots are 1,1 >>> np.roots([1,-2,1]) array([1., 1.]) # Similarly x^2 - 4 = 0 has roots as x=±2 >>> np.roots([1,0,-4]) array([-2., 2.])
比较
举例:
# Using comparison operators will create boolean NumPy arrays z = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) c = z < 6 print(c) >>> [ TrueTrueTrueTrueTrueFalseFalseFalseFalseFalse]
基本的统计
举例:
# Statistics of an array a = np.array([1, 1, 2, 5, 8, 10, 11, 12]) # Standard deviation print(np.std(a)) >>> 4.2938910093294167 # Median print(np.median(a)) >>> 6.5
更多
6.切片和子集
举例:
b = np.array([(1, 2, 3), (4, 5, 6)])
# The index *before* the comma refers to *rows*, # the index *after* the comma refers to *columns* print(b[0:1, 2]) >>> [3]
print(b[:len(b), 2]) >>> [36]
print(b[0, :]) >>> [123]
print(b[0, 2:]) >>> [3]
print(b[:, 0]) >>> [14]
c = np.array([(1, 2, 3), (4, 5, 6)]) d = c[1:2, 0:2] print(d) >>> [[45]]