Numpy 的 take(~)
方法用於訪問數組的值、行和列。
參數
1. a
| array_like
要對其執行方法的數組。
2. indices
| number
或 array_like
要獲取的值的索引。如果您提供 number
類型,那麽您將訪問數組中的單個值、行或列。如果提供了 array_like
類型,則您將訪問多個行/列。
3. axis
| number
| optional
選擇值所沿的軸。默認情況下, axis=None
,即您的輸入數組 a
將被視為扁平數組。
返回值
根據參數的不同,返回類型會有所不同。
-
如果沒有提供
axis
,那麽您會得到一個數字,因為您隻是訪問單個值。 -
如果提供了
axis
,那麽您將獲得一個 Numpy 數組,因為您正在訪問行或列。
例子
訪問矩陣中的單個值
x = [[4,5,6], [7,8,9]]
np.take(x, 1)
5
請記住,如果您為第二個參數提供 number
類型,則 Numpy 會將您的輸入數組視為展平數組,即 x=[4,5,6,7,8,9]
。在此示例中,我們采用該展平數組的第一個索引,因此返回值 5。
訪問矩陣的單行
要訪問矩陣的行,請提供參數 axis=0
。
x = [[4,5,6], [7,8,9]]
np.take(x, 1, axis=0)
array([7, 8, 9])
為了澄清這段代碼的作用,我們隻是獲取第二行(即行也遵循索引順序,所以這就是我們將 1 設置為第二個參數的原因):
訪問矩陣的單列
要訪問矩陣的列,請提供參數 axis=1
。
x = [[4,5,6], [7,8,9]]
np.take(x, 1, axis=1)
array([5, 8])
為了澄清這段代碼的作用,我們隻是獲取第二列(即列也遵循索引順序,所以這就是我們將 1 設置為第二個參數的原因):
訪問矩陣的多行
要訪問矩陣的多列,請提供參數 axis=0
,並為第二個參數提供類型 array-like
:
x = [[4,5,6], [7,8,9]]
np.take(x, [0,1], axis=0)
array([[4, 5, 6],
[7, 8, 9]])
我們正在訪問第一行和第二行,如下所示:
訪問矩陣的多列
要訪問矩陣的多列,請提供參數 axis=1
,並為第二個參數提供類型 array-like
:
x = [[4,5,6], [7,8,9]]
np.take(x, [0,2], axis=1)
array([[4, 6],
[7, 9]])
我們正在訪問第一列和第三列,如下所示:
相關用法
- Python Tableau tasks.delete用法及代碼示例
- Python Tableau tasks.run用法及代碼示例
- Python Tableau tasks.get用法及代碼示例
- Python Tableau tasks.get_by_id用法及代碼示例
- Python NumPy tan方法用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代碼示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代碼示例
- Python torchaudio.transforms.Fade用法及代碼示例
- Python tf.compat.v1.data.TFRecordDataset.interleave用法及代碼示例
- Python tf.summary.scalar用法及代碼示例
- Python tf.linalg.LinearOperatorFullMatrix.matvec用法及代碼示例
- Python tf.linalg.LinearOperatorToeplitz.solve用法及代碼示例
- Python tf.raw_ops.TPUReplicatedInput用法及代碼示例
- Python tf.raw_ops.Bitcast用法及代碼示例
- Python tf.compat.v1.distributions.Bernoulli.cross_entropy用法及代碼示例
- Python Pandas tseries.offsets.CustomBusinessHour.onOffset用法及代碼示例
- Python torch.special.gammaincc用法及代碼示例
- Python typing.get_type_hints用法及代碼示例
- Python tensorflow.math.xlog1py()用法及代碼示例
- Python tf.compat.v1.Variable.eval用法及代碼示例
- Python tf.compat.v1.train.FtrlOptimizer.compute_gradients用法及代碼示例
- Python tf.distribute.OneDeviceStrategy.experimental_distribute_values_from_function用法及代碼示例
- Python tf.math.special.fresnel_cos用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 NumPy | take method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。