1. 程式人生 > 實用技巧 >Nump庫的基本使用

Nump庫的基本使用

Nump庫的基本使用

 

庫的匯入 PyCharm

file - Setting - Project interpreter - + - (Searh what you need) - Install Package

 

多維陣列

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(a)
print("-------------")
a[1, 1]=10
print(a)
print("-------------")
# dtype獲得元素屬性
print(a.dtype)
# shape獲得陣列大小
print(a.shape)

 

結構陣列 dtype

與C語言的struct類似,結構中的欄位佔據連續的記憶體空間,每個結構體佔用的記憶體大小相同

注:

np.dtype({})中,必須是'names'和'formats',不允許自己給名,否則會報出如下錯誤

ValueError: entry not a 2- or 3- tuple

 

使用示例

import numpy as np

persontype = np.dtype({
    'names': ['name', 'age', 'chinese', 'math', 'english'],
    'formats': ['S32', 'i', 'i', 'i', 'f']})

students = np.array([
    ("zhangsan", 32, 75, 100, 90), ("lisi", 24, 85, 96, 88.5),
    ("wangwu", 28, 85, 92, 96.5), ("wangmazi", 29, 65, 85, 100)
], dtype=persontype)

ages = students[:]['age']
chinesemarks = students[:]['chinese']
mathmarks = students[:]['math']
englishmarks = students[:]['english']

print("平均年齡為:", np.mean(ages))
print("語文平均分為:", np.mean(chinesemarks))
print("數學平均分為:", np.mean(mathmarks))
print("英語平均分為:", np.mean(englishmarks))
print(students.dtype)
print(students.shape)

結果返回

平均年齡為: 28.25
語文平均分為: 77.5
數學平均分為: 93.25
英語平均分為: 93.75
[('name', 'S32'), ('age', '<i4'), ('chinese', '<i4'), ('math', '<i4'), ('english', '<f4')]
(4,)

 

連續陣列

  • np.arange:建立等差陣列,指定初始值、終值、步長,結果包含終值
  • np.linspce:建立等差陣列,指定初始值、終值、元素個數,結果不包含終值
# 建立等差陣列
# np.arange() 初始值、終值、步長 預設不包括終值
x1 = np.arange(1,11,2)
# np.linspace() 初始值、終止、元素個數 預設包括終值
x2 = np.linspace(1,9,5)

 

小技巧

提高記憶體和計算資源利用率的技巧:

避免隱式拷貝,而不是採用就地操作方式,如

儘量使用 x*=2
而不是 y=x*2

 

Numpy還有強大的統計函式,詳見,如果遇到空值NaN,會自動排除