numpy常用函数

记录一下自己常用的常用函数和常规操作。

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., (2, 3) or 2.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值