Numpy的重要性
学习人工智能,不就是想要做数据分析。 选择 Python 这门语言的确可以让你相对快速地上车做数据分析。而 Numpy 正是把 Python 捧上神坛的第三方库之一。
Numpy用武之地
使用 Numpy 的场景:
- 需要批量处理数据的时候
- 机器学习,人工智能这些需要进行海量数据运算处理的地方
- 写游戏里面的物体运行逻辑时,经常涉及到矩阵、向量运算
- 机器人模拟环境,背后的环境反馈信息,全是靠批量数据算出来的
- 任何需要做统计的时候(爬虫爬完了信息后)
- 画图表之前,要对数据做一轮批量处理
- Blah blah
Numpy用法
导库(包)
import numpy as np
基本操作目录
- 创建数据
- np.array()
- array.ndim
- 添加数据
- np.concatenate()
- np.expand_dims()
- 合并数据
- np.concatenate()
- np.vstack()
- np.hstack()
- 观察形态
- array.size
- array.shape
创建数据
# 一维
cars = np.array([1, 2, 3, 4, 5])
print(cars.ndim) # 返回 1
# cars.ndim 会返回给你一个维度的属性
# 二维:
LotsCars = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [3, 4, 5, 6]])
print('维度为:', LotsCars.ndim)
print('LotsCars的数据为\n', LotsCars)
print(LotsCars[0], " ", LotsCars[1], " ", LotsCars[2])
# 三维:
ALotsCars = np.array([
[
[1,2,3,4],[2,3,4,5],[3,4,5,6]],
[
[4,5,6,7],[5,6,7,8],[6,7,8,9]]
])
print('维度为:\n', ALotsCars.ndim) # # 返回 3
print('ALotsCars的数据为\n', ALotsCars)
print(ALotsCars[0][1].ndim) # 返回 1
print(ALotsCars[1].ndim) # 返回 2
添加数据
car1 = np.array([1,2,3,4])
car2 = np.array([5,6,7,8])
cars3 = np.concatenate([car1,car2])
print(cars3)
# 输出 [1 2 3 4 5 6 7 8]
# 首先需要把它们都变成二维,下面这两种方法都可以加维度
# np.expand_dims
test1 = np.array([5, 10, 12, 6])
test1 = np.expand_dims(test1, 0)
# test2[np.newaxis, :]
test2 = np.array([5.1, 8.2, 11, 6.3])
test2 = test2[np.newaxis, :]
# 然后再在第一个维度上叠加
all_tests = np.concatenate([test1, test2])
print("括展后\n", all_tests)
# test1加维度后 [[ 5 10 12 6]]
# test2加维度后 [[ 5.1 8.2 11. 6.3]]
# 括展后
# [[ 5. 10. 12. 6. ]
# [ 5.1 8.2 11. 6.3]]
合并数据
print("第一维度叠加:\n", np.concatenate([all_tests, all_tests], axis=0))
print("第二维度叠加:\n", np.concatenate([all_tests, all_tests], axis=1))
# 第一维度叠加:
# [[ 5. 10. 12. 6. ]
# [ 5.1 8.2 11. 6.3]
# [ 5. 10. 12. 6. ]
# [ 5.1 8.2 11. 6.3]]
# 第二维度叠加:
# [[ 5. 10. 12. 6. 5. 10. 12. 6. ]
# [ 5.1 8.2 11. 6.3 5.1 8.2 11. 6.3]]
# 一个更清晰的例子:
a = np.array([
[1,2,3],
[4,5,6]
])
b = np.array([
[7,8],
[9,10]
])
print(np.concatenate([a,b], axis=1)) # 这个没问题
# print(np.concatenate([a,b], axis=0)) # 这个会报错
# vstack()和hstack()
a = np.array([
[1,2],
[3,4]
])
b = np.array([
[5,6],
[7,8]
])
print("竖直合并\n", np.vstack([a, b]))
print("水平合并\n", np.hstack([a, b]))
观察形态
除了 np.ndim 来查看数据的形态,其实我们有时候还想更加了解数据的细节问题,比如这个数据的大小,规格。方便我们管理这些数据。
比如当我想知道到底有多少车辆测试数据时,你可能会通过遍历的方法来计数。
cars = np.array([
[5, 10, 12, 6],
[5.1, 8.2, 11, 6.3],
[4.4, 9.1, 10, 6.6]
])
count = 0
for i in range(len(cars)):
for j in range(len(cars[i])):
count += 1
print("总共多少测试数据:", count)
# 其实 Numpy 还有更好用的方式获取总个数。使用 cars.size
print("总共多少测试数据:", cars.size)
更进一步,我不光想知道总数据,我还想知道当前有多少次测试(第一个维度,行),和在多少辆车上测试了(第二个维度,列)。怎么办?
print("第一个维度:", cars.shape[0])
print("第二个维度:", cars.shape[1])
print("所有维度:", cars.shape)
# 第一个维度: 3
# 第二个维度: 4
# 所有维度: (3, 4)