乾貨 | 50題帶你玩轉numpy
這是在stackoverflow和numpy文件裡彙總的numpy練習題,目的是為新老使用者提供快速參考。
1。 Import the numpy package under the name
np
(★☆☆)
匯入numpy包,命名為
np
import
numpy
as
np
2。 Print the numpy version and the configuration (★☆☆)
列印numpy版本和配置
(
np
。
__version__
)
np
。
show_config
()
3。 Create a null vector of size 10 (★☆☆)
建立一個10*10的0填充的陣列
Z
=
np
。
zeros
(
10
)
(
Z
)
4。 How to find the memory size of any array (★☆☆)
如何檢視陣列佔記憶體大小
Z
=
np
。
zeros
((
10
,
10
))
(
“
%d
bytes”
%
(
Z
。
size
*
Z
。
itemsize
))
5。 How to get the documentation of the numpy add function from the command line? (★☆☆)
如何在命令列下檢視numpy add函式文件
%
run
`
python
-
c
“import numpy; numpy。info(numpy。add)”
`
6。 Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
建立一個長度為10的0陣列,第5個值為1
Z
=
np
。
zeros
(
10
)
Z
[
4
]
=
1
(
Z
)
7。 Create a vector with values ranging from 10 to 49 (★☆☆)
建立一個值從10到49的陣列
Z
=
np
。
arange
(
10
,
50
)
(
Z
)
8。 Reverse a vector (first element becomes last) (★☆☆)
反轉陣列(第一個元素變成最後一個)
Z
=
np
。
arange
(
50
)
Z
=
Z
[::
-
1
]
(
Z
)
9。 Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
建立一個從0~8的3*3矩陣
Z
=
np
。
arange
(
9
)
。
reshape
(
3
,
3
)
(
Z
)
10。 Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
從[1,2,0,0,4,0]中找到非0元素的索引
nz
=
np
。
nonzero
([
1
,
2
,
0
,
0
,
4
,
0
])
(
nz
)
11。 Create a 3x3 identity matrix (★☆☆)
生成一個3*3的對角矩陣
Z
=
np
。
eye
(
3
)
(
Z
)
12。 Create a 3x3x3 array with random values (★☆☆)
建立一個3
3
3的隨機值陣列
Z
=
np
。
random
。
random
((
3
,
3
,
3
))
(
Z
)
13。 Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)
建立一個10*10的隨機值陣列,並找到最大最小值
Z
=
np
。
random
。
random
((
10
,
10
))
Zmin
,
Zmax
=
Z
。
min
(),
Z
。
max
()
(
Zmin
,
Zmax
)
14。 Create a random vector of size 30 and find the mean value (★☆☆)
建立一個長度為30的隨機值陣列,並找到平均值
Z
=
np
。
random
。
random
(
30
)
m
=
Z
。
mean
()
(
m
)
15。 Create a 2d array with 1 on the border and 0 inside (★☆☆)
建立一個四邊為1,中間為0的二維陣列,
Z
=
np
。
ones
((
10
,
10
))
Z
[
1
:
-
1
,
1
:
-
1
]
=
0
(
Z
)
16。 How to add a border (filled with 0‘s) around an existing array? (★☆☆)
如何給一個已經存在的陣列新增邊(填充0)
Z
=
np
。
ones
((
5
,
5
))
Z
=
np
。
pad
(
Z
,
pad_width
=
1
,
mode
=
’constant‘
,
constant_values
=
0
)
(
Z
)
17。 What is the result of the following expression? (★☆☆)
看看下面表示式的結果是什麼?
(
0
*
np
。
nan
)
(
np
。
nan
==
np
。
nan
)
(
np
。
inf
>
np
。
nan
)
(
np
。
nan
-
np
。
nan
)
(
np
。
nan
in
set
([
np
。
nan
]))
(
0。3
==
3
*
0。1
)
18。 Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
建立一個5*5矩陣,對角線下方值為1,2,3,4
Z
=
np
。
diag
(
1
+
np
。
arange
(
4
),
k
=-
1
)
(
Z
)
19。 Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
建立一個8*8矩陣,並用棋盤圖案填充
Z
=
np
。
zeros
((
8
,
8
),
dtype
=
int
)
Z
[
1
::
2
,::
2
]
=
1
Z
[::
2
,
1
::
2
]
=
1
(
Z
)
20。 Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
給定一個6
7
8的三維矩陣,求100個元素的索引是什麼?
(
np
。
unravel_index
(
99
,(
6
,
7
,
8
)))
21。 Create a checkerboard 8x8 matrix using the tile function (★☆☆)
使用tile函式建立8*8的棋盤矩陣
Z
=
np
。
tile
(
np
。
array
([[
0
,
1
],[
1
,
0
]]),
(
4
,
4
))
(
Z
)
22。 Normalize a 5x5 random matrix (★☆☆)
對一個5*5矩陣標準化處理
Z
=
np
。
random
。
random
((
5
,
5
))
Z
=
(
Z
-
np
。
mean
(
Z
))
/
(
np
。
std
(
Z
))
(
Z
)
23。 Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)
新建一個dtype型別用來描述一個顏色(RGBA)
color = np。dtype([(“r”, np。ubyte, 1),
(“g”, np。ubyte, 1),
(“b”, np。ubyte, 1),
(“a”, np。ubyte, 1)])
24。 Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
5*3矩陣和3*2矩陣相乘
Z
=
np
。
dot
(
np
。
ones
((
5
,
3
)),
np
。
ones
((
3
,
2
)))
(
Z
)
# Alternative solution, in Python 3。5 and above
Z
=
np
。
ones
((
5
,
3
))
@
np
。
ones
((
3
,
2
))
(
Z
)
25。 Given a 1D array, negate all elements which are between 3 and 8, in place。 (★☆☆)
給定一個一維陣列,將第3~8個元素取反
# Author: Evgeni Burovski
Z
=
np
。
arange
(
11
)
Z
[(
3
<
Z
)
&
(
Z
<=
8
)]
*=
-
1
(
Z
)
26。 What is the output of the following script? (★☆☆)
看看下面指令碼的輸出是什麼?
# Author: Jake VanderPlas
(
sum
(
range
(
5
),
-
1
))
from
numpy
import
*
(
sum
(
range
(
5
),
-
1
))
27。 Consider an integer vector Z, which of these expressions are legal? (★☆☆)
給定一個整數陣列Z,看看下面哪個表示式是合法的?
Z
**
Z
2
<<
Z
>>
2
Z
<-
Z
1
j
*
Z
Z
/
1
/
1
Z
<
Z
>
Z
28。 What are the result of the following expressions?
下面表示式的結果是什麼?
(
np
。
array
(
0
)
/
np
。
array
(
0
))
(
np
。
array
(
0
)
//
np
。
array
(
0
))
(
np
。
array
([
np
。
nan
])
。
astype
(
int
)
。
astype
(
float
))
29。 How to round away from zero a float array ? (★☆☆)
如何對陣列進行四捨五入操作?
# Author: Charles R Harris
Z
=
np
。
random
。
uniform
(
-
10
,
+
10
,
10
)
(
np
。
copysign
(
np
。
ceil
(
np
。
abs
(
Z
)),
Z
))
30。 How to find common values between two arrays? (★☆☆)
如何找出兩個陣列的共同值?
Z1
=
np
。
random
。
randint
(
0
,
10
,
10
)
Z2
=
np
。
random
。
randint
(
0
,
10
,
10
)
(
np
。
intersect1d
(
Z1
,
Z2
))
31。 How to ignore all numpy warnings (not recommended)? (★☆☆)
如何忽略所有numpy警告?
# Suicide mode on
defaults
=
np
。
seterr
(
all
=
“ignore”
)
Z
=
np
。
ones
(
1
)
/
0
# Back to sanity
_
=
np
。
seterr
(
**
defaults
)
An equivalent way, with a context manager:
with
np
。
errstate
(
divide
=
’ignore‘
):
Z
=
np
。
ones
(
1
)
/
0
32。 Is the following expressions true? (★☆☆)
下面表示式正確嗎?
np
。
sqrt
(
-
1
)
==
np
。
emath
。
sqrt
(
-
1
)
33。 How to get the dates of yesterday, today and tomorrow? (★☆☆)
如何獲得昨天、今天、明天的日期?
yesterday
=
np
。
datetime64
(
’today‘
,
’D‘
)
-
np
。
timedelta64
(
1
,
’D‘
)
today
=
np
。
datetime64
(
’today‘
,
’D‘
)
tomorrow
=
np
。
datetime64
(
’today‘
,
’D‘
)
+
np
。
timedelta64
(
1
,
’D‘
)
34。 How to get all the dates corresponding to the month of July 2016? (★★☆)
如何獲得2016年7月對應的所有日期?
Z
=
np
。
arange
(
’2016-07‘
,
’2016-08‘
,
dtype
=
’datetime64[D]‘
)
(
Z
)
35。 How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
如何計算((A+B)*(-A/2)) ?
A
=
np
。
ones
(
3
)
*
1
B
=
np
。
ones
(
3
)
*
2
C
=
np
。
ones
(
3
)
*
3
np
。
add
(
A
,
B
,
out
=
B
)
np
。
divide
(
A
,
2
,
out
=
A
)
np
。
negative
(
A
,
out
=
A
)
np
。
multiply
(
A
,
B
,
out
=
A
)
36。 Extract the integer part of a random array using 5 different methods (★★☆)
提取隨機數列整數部分的五種方法
Z
=
np
。
random
。
uniform
(
0
,
10
,
10
)
(
Z
-
Z
%
1
)
(
np
。
floor
(
Z
))
(
np
。
ceil
(
Z
)
-
1
)
(
Z
。
astype
(
int
))
(
np
。
trunc
(
Z
))
37。 Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
建立一個5*5的矩陣,每一行值為1~4
Z
=
np
。
zeros
((
5
,
5
))
Z
+=
np
。
arange
(
5
)
(
Z
)
38。 Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
給定一個生成器函式,可以生成10個整數,使用它來建立一個數組
def
generate
():
for
x
in
range
(
10
):
yield
x
Z
=
np
。
fromiter
(
generate
(),
dtype
=
float
,
count
=-
1
)
(
Z
)
39。 Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
建立一個長度為10的陣列,值為0~1之間,不包含首尾
Z
=
np
。
linspace
(
0
,
1
,
11
,
endpoint
=
False
)[
1
:]
(
Z
)
40。 Create a random vector of size 10 and sort it (★★☆)
建立一個長度為10的陣列,並做排序操作
Z
=
np
。
random
。
random
(
10
)
Z
。
sort
()
(
Z
)
41。 How to sum a small array faster than np。sum? (★★☆)
如何對一個數組進行相加操作,並且速度快於np。sum
# Author: Evgeni Burovski
Z
=
np
。
arange
(
10
)
np
。
add
。
reduce
(
Z
)
42。 Consider two random array A and B, check if they are equal (★★☆)
給定兩個隨機陣列A和B,驗證它們是否相等
A
=
np
。
random
。
randint
(
0
,
2
,
5
)
B
=
np
。
random
。
randint
(
0
,
2
,
5
)
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal
=
np
。
allclose
(
A
,
B
)
(
equal
)
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal
=
np
。
array_equal
(
A
,
B
)
(
equal
)
43。 Make an array immutable (read-only) (★★☆)
使一個數組不變(只讀)
Z
=
np
。
zeros
(
10
)
Z
。
flags
。
writeable
=
False
Z
[
0
]
=
1
44。 Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
給定表示笛卡爾座標的一個10*2的隨機矩陣,將其轉換為極座標
Z
=
np
。
random
。
random
((
10
,
2
))
X
,
Y
=
Z
[:,
0
],
Z
[:,
1
]
R
=
np
。
sqrt
(
X
**
2
+
Y
**
2
)
T
=
np
。
arctan2
(
Y
,
X
)
(
R
)
(
T
)
45。 Create random vector of size 10 and replace the maximum value by 0 (★★☆)
建立一個長度為10的隨機矩陣,並將最大值替換為0
Z
=
np
。
random
。
random
(
10
)
Z
[
Z
。
argmax
()]
=
0
(
Z
)
46。 Create a structured array with
x
and
y
coordinates covering the [0,1]x[0,1] area (★★☆)
建立具有x和y座標的結構化陣列,它們覆蓋[0,1] x [0,1]區域
Z
=
np
。
zeros
((
5
,
5
),
[(
’x‘
,
float
),(
’y‘
,
float
)])
Z
[
’x‘
],
Z
[
’y‘
]
=
np
。
meshgrid
(
np
。
linspace
(
0
,
1
,
5
),
np
。
linspace
(
0
,
1
,
5
))
(
Z
)
47。 Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))
給定兩個陣列X和Y,構造柯西矩陣C(Cij = 1 /(xi-yj))
# Author: Evgeni Burovski
X
=
np
。
arange
(
8
)
Y
=
X
+
0。5
C
=
1。0
/
np
。
subtract
。
outer
(
X
,
Y
)
(
np
。
linalg
。
det
(
C
))
48。 Print the minimum and maximum representable value for each numpy scalar type (★★☆)
列印每種numpy標量型別的最小和最大可表示值
for
dtype
in
[
np
。
int8
,
np
。
int32
,
np
。
int64
]:
(
np
。
iinfo
(
dtype
)
。
min
)
(
np
。
iinfo
(
dtype
)
。
max
)
for
dtype
in
[
np
。
float32
,
np
。
float64
]:
(
np
。
finfo
(
dtype
)
。
min
)
(
np
。
finfo
(
dtype
)
。
max
)
(
np
。
finfo
(
dtype
)
。
eps
)
49。 How to print all the values of an array? (★★☆)
如何列印陣列中所有值
np
。
set_printoptions
(
threshold
=
np
。
nan
)
Z
=
np
。
zeros
((
16
,
16
))
(
Z
)
50。 How to find the closest value (to a given scalar) in a vector? (★★☆)
如何在陣列中找到最接近給定值的值
Z
=
np
。
arange
(
100
)
v
=
np
。
random
。
uniform
(
0
,
100
)
index
=
(
np
。
abs
(
Z
-
v
))
。
argmin
()
(
Z
[
index
])
本文翻譯自:
https://
github。com/rougier/nump
y-100