Python之Numpy庫(3)

1、numpy中變換元素的類型

numbers = numpy.array(['1', '2', '3'])
print(numbers.dtype)
print(numbers)
numbers = numbers.astype(float)
print(numbers.dtype)
print(numbers)

#運行結果:
<U1
['1' '2' '3']
float64
[1. 2. 3.]

OK,通過dtype方法我們可以看到,最初的時候,我們傳入的數組中,元素類型爲str,通過astype()屬性,我們可以將元素的類型進行轉換。

2、取數組中的極值操作

vector = numpy.array([5, 10, 15, 20])
print(vector.min())
print(vector.max())

#運行結果:
5
20

通過min()和max()方法來求數組中的最大值和最小值。

3、按行求和或按列求和

matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(matrix.sum(axis=1))

#運行結果:
[ 30  75 120]

我們可以看出來5+10+15=30,  20+25+30=75,35+40+45=120。好像是對每一行進行了相加。我們再看下面的代碼:

matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(matrix.sum(axis=0))

#運行結果:
[60 75 90]

我們可以看下,5+20+35=60,  10+25+40=75,  15+30+45=90。嗯,剛好等於每一列的和。

上述代碼中,axis代表了一個維度,axis=1代表行,axis=0代表列

4、對numpy中的矩陣進行變換

import numpy as np
print(np.arange(15))
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)

#運行結果:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
(3,5)

採用np.arange()方法,則生成一個0-14的數組。使用reshape()方法將數組變爲矩陣,reshape(3,5)代表變爲3行5列。

我們可以通過shape方法可以看出,該矩陣爲3行5列。

5、ndim & dtype.name & size屬性

a = np.arange(15).reshape(3, 5)
print(a.ndim)

#運行結果:
2

通過a.ndim查取數組的維度。

a = np.arange(15).reshape(3, 5)
print(a.dtype.name)

#運行結果:
int32

通過a.dtype.name獲得元素的類型。

a = np.arange(15).reshape(3, 5)
print(a.size)

#運行結果:
15

通過a.size獲得元素的個數。

 

6、獲得元素爲0或者1的矩陣

a = np.zeros((3, 4))
print(a)

#運行結果:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

通過np.zeros((3,4))獲得一個3行4列的矩陣,矩陣中每個元素都爲0。特別要注意的是,傳入np.zeros()中的是(3,4)的元組,不能直接將3,4傳進去,不然會報錯。

a = np.ones((2, 3, 4))
print(a)

#運行結果
[[[1. 1. 1. 1.]
  [1. 1. 1. 1.]
  [1. 1. 1. 1.]]

 [[1. 1. 1. 1.]
  [1. 1. 1. 1.]
  [1. 1. 1. 1.]]]

同理,我們用np.ones()可以構造一個值全部是1的矩陣。(2,3,4)說明這個矩陣是三維的。

但是我們發現,爲什麼1後面有個小數點呢?其實,我們還可以將np.ones()再優化一下,確認元素的類型,比如:

a = np.ones((2, 3, 4), dtype=int)
print(a)

#運行結果:
[[[1 1 1 1]
  [1 1 1 1]
  [1 1 1 1]]

 [[1 1 1 1]
  [1 1 1 1]
  [1 1 1 1]]]

果然,運行結果就沒有小數點了。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章