记录一下自己常用的常用函数和常规操作。
1.numpy.full
numpy.
full
(shape, fill_value, dtype=None, order='C')[source]
Return a new array of given shape and type, filled with fill_value.
Parameters: | shape : int or sequence of ints Shape of the new array, e.g., fill_value : scalar Fill value. dtype : data-type, optional The desired data-type for the array The default, None, means np.array(fill_value).dtype. order : {‘C’, ‘F’}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. |
---|---|
Returns: | out : ndarray Array of fill_value with the given shape, dtype, and order. |
字面意思,用某一个值来填满数组。
2.numpy.where
numpy.
where
(condition[, x, y])
Return elements chosen from x or y depending on condition.
Note
When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero()
. Using nonzero
directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.
Parameters: | condition : array_like, bool Where True, yield x, otherwise yield y. x, y : array_like Values from which to choose. x, y and condition need to be broadcastable to some shape. |
---|---|
Returns: | out : ndarray An array with elements from x where condition is True, and elements from y elsewhere. |
当条件满足的时候,选取x,不满足,选取y,返回结果。
从上面结果可以看出 条件 输出的结果是对应a的bool数组。其中true值,会被x中对应位置数值代替,false会被y中数值代替,将替换的结果返回。
要么x,y与a的形状一致,要么为特定值,可以从一下结果看出。
而且,a本身值是不变的。
3. 如何获取两个numpy数组之间的公共项?
难度等级:L2
问题:获取数组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])
期望的输出:
array([2, 4])
答案:
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])
np.intersect1d(a,b)
# > array([2, 4])
4. 如何从一个数组中删除存在于另一个数组中的项?
难度等级:L2
问题:从数组a中删除数组b中的所有项。
给定:
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
期望的输出:
array([1,2,3,4])
答案:
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
# From 'a' remove all of 'b'
np.setdiff1d(a,b)
# > array([1, 2, 3, 4])
5. 如何得到两个数组元素匹配的位置?
难度等级:L2
问题:获取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])
期望的输出:
# > (array([1, 3, 5, 7]),)
答案:
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])
np.where(a == b)
# > (array([1, 3, 5, 7]),)
6. 设置输出
np.set_printoptions(precision=4) #设置输出小数点后个数
np.set_printoptions(suppress=True) #设置是否使用科学计数法法,默认False,使用科学计数法
持续更新中 19/05/09