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,会自动排除

猜你喜欢

转载自www.cnblogs.com/G-Aurora/p/13380304.html
今日推荐