App下載

numpy 相關(guān)函數(shù)使用

猿友 2021-01-09 10:22:00 瀏覽數(shù) (2291)
反饋

np.where

首先強(qiáng)調(diào)一下,where()函數(shù)對(duì)于不同的輸入,返回的值是不同的。

1、當(dāng)數(shù)組是一維數(shù)組時(shí),返回的值是一維的索引,所以只有一組索引數(shù)組;

2、當(dāng)數(shù)組是二維數(shù)組時(shí),滿足條件的數(shù)組值返回的是值的位置索引,因此會(huì)有兩組索引數(shù)組來表示值的位置,下面舉例說明:

import numpy as np
a=np.reshape(np.arange(20),(4,5))

a
array([[ 0,  1,  2,  3,  4],
      [ 5,  6,  7,  8,  9],
      [10, 11, 12, 13, 14],
      [15, 16, 17, 18, 19]])

b = np.where(a>10)
b
(array([2, 2, 2, 2, 3, 3, 3, 3, 3], dtype=int64), array([1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64))
b[0][:]
array([2, 2, 2, 2, 3, 3, 3, 3, 3], dtype=int64)
b[0]
array([2, 2, 2, 2, 3, 3, 3, 3, 3], dtype=int64)
b[1]
array([1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64)

a是一個(gè)二維數(shù)組,b就是返回的索引,索引分為行索引和列索引兩個(gè)部分,b[0]是行索引,b[1]是列索引。

np.tile

他的功能是重復(fù)某個(gè)數(shù)組。比如tile(A,n),功能是將數(shù)組A重復(fù)n次,構(gòu)成一個(gè)新的數(shù)組.例子:

import numpy as np
a = [1,2,3]
b  = np.tile(a, (1, 4))
b
array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]])
b  = np.tile(a, 4)
b
array([1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
d  = np.tile(a, (2, 4))
d
array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3],
       [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]])

從上面的例子我們可以看到,其中 b = np.tile(a, (1, 4))生成的是一個(gè)二維數(shù)組,而b = np.tile(a, 4)生成的是一個(gè)一維數(shù)組,都是把a(bǔ)重復(fù)4次。


0 人點(diǎn)贊