Python_numpy

1.导入包

import numpy # 直接导入整个包
import numpy as np # 导入numpy包并且取别名np
from numpy import array # 从numpy中单独导入array

2.array()

把list变为array型的list

>>> height = [1.73,1.68,1.71,1.98,1.79]
>>> weight = [65.4,59.2,63.6,88.4,68.7]
>>> np_height = np.array(height)
>>> np_weight = np.array(weight)
>>> np_height
array([1.73, 1.68, 1.71, 1.98, 1.79])
>>> np_weight
array([65.4, 59.2, 63.6, 88.4, 68.7])

对array进行计算

>>> bmi = np_weight / np_height ** 2
>>> bmi
array([21.85171573, 20.97505669, 21.75028214, 22.54871952, 21.44127836])
>>>

3.numpy中的array内只能有一种数据类型

>>> np.array([1.0,'is',True])
array(['1.0', 'is', 'True'], dtype='|S32')

4.list和array的对比

>>> list = [1,2,3]
>>> np_list = np.array([1,2,3])
>>> list + list
[1, 2, 3, 1, 2, 3]
>>> np_list + np_list
array([2, 4, 6])
>>>

5.对array中的值进行筛选

>>> bmi
array([21.85171573, 20.97505669, 21.75028214, 22.54871952, 21.44127836])
>>> bmi > 22
array([False, False, False,  True, False])
>>> bmi[bmi > 22]
array([22.54871952]) 
>>>

6.二维array

image.png
>>> np_2d = np.array([[1.73,1.68,1.71,1.89,1.79],[65.4,59.2,63.6,88.4,68.7]]) # 定义一个二维的array
>>> np_2d
array([[ 1.73,  1.68,  1.71,  1.89,  1.79],
       [65.4 , 59.2 , 63.6 , 88.4 , 68.7 ]])
>>> np_2d[0][2] # 第一种形式:先确定行号,再确定列号
1.71
>>> np_2d[0,2] # 第二种形式:用一个方括号中间加逗号区分行号和列号
1.71
>>> np_2d[:,1:3] # 在二维数组中使用切片的方法
array([[ 1.68,  1.71],
       [59.2 , 63.6 ]])
>>> np_2d[1,:]
array([65.4, 59.2, 63.6, 88.4, 68.7])
>>>

你可能感兴趣的:(Python_numpy)