课程地址:
https://aistudio.baidu.com/aistudio/course/introduce/1224
1 python json
代码:
import json
data = [{'b': 1, 'd': 2, 'a': 1, 'c': 5, 'e': 90}]
# json.dumps 用于将 Python 对象编码成 JSON 字符串
json_1 = json.dumps(data)
print(json_1)
# sort_keys=True表示按照字典排序(a到z)输出。
# indent参数,代表缩进的位数。
# separators参数的作用是去掉,和:后面的空格,传输过程中数据越精简越好。
json_2 = json.dumps(data, sort_keys=True, indent=2, separators=(',', ':'))
print(json_2)
jsonData = '{"b": 1, "d": 2, "a": 1, "c": 5, "e": 90}'
# json.loads 用于解码 JSON 数据。
# 该函数返回Python字段的数据类型。
# 将string转换为dict
text = json.loads(jsonData)
print(text)
结果图:
2 numpy库
代码:
import numpy as np
zeroarray = np.zeros((2,3))
print(zeroarray)
onearray = np.ones((2, 3), dtype='int64')
print(onearray)
emptyarray = np.empty((2, 3))
print(emptyarray)
print(emptyarray.ndim)
# 数组形状
print(emptyarray.shape)
# 数组元素个数
print(emptyarray.size)
# 数组元素类型
print(emptyarray.dtype)
# 大小相等的数组之间的任何算术运算都会将运算应用到元素级
print(zeroarray + onearray)
print(zeroarray * onearray)
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.ones([3, 2], dtype=np.int64)
# 矩阵乘法
print(np.dot(arr1, arr2))
pass
结果图:
代码:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
# axis=1,每一行求和
print(np.sum(arr, axis=1))
# axie=0,每一列求和
print(np.sum(arr, axis=0))
print(np.max(arr))
print(np.min(arr))
# 均值
print(np.mean(arr))
# 最大值索引
print(np.argmax(arr))
print(np.argmin(arr))
# 转置
print(arr.transpose())
pass
结果图:
3 pandas库
代码:
import pandas as pd
import numpy as np
# Pandas核心数据结构:Series & DataFrame
# Series可以理解为带标签的一维数组,允许索引重复
s = pd.Series(['a','b','c','d','e'], index=[1,2,1,4,5])
print(s)
print(s[1])
# 用字典实例化
s0 = pd.Series({'b': 1, 'a': 0, 'c': 2})
print(s0)
s1 = pd.Series(np.array([1,2,3,4,5]), index=['a', 'b', 'c', 'd', 'e'])
# 对应元素相加
print(s1 + s1)
print(s1.values)
print(s1.index)
print(s1[2:])
print(s1[:-2])
print(s1[2:] + s1[:-2])
pass
效果图:
代码:
import pandas as pd
import numpy as np
# Pandas核心数据结构:Series & DataFrame
data = {'year': [2020, 2021, 2022], 'month': [9,10,11], 'day':[20,21,22]}
frame = pd.DataFrame(data)
print(frame)
# 按照指定顺序进行排列
frame0 = pd.DataFrame(data, columns=['day', 'month', 'year'])
print(frame0)
# 传入的列在数据中找不到,就会产生NAN值
frame1 = pd.DataFrame(data, columns=['year', 'month', 'day', 'emo'], index=['one', 'two', 'three'])
print(frame1)
print(frame1['year'])
frame1['emo'] = 'happy'
print(frame1)
frame1['emo'] = np.arange(3)
print(frame1)
# 用Series字典或字典生成 DataFrame
d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
print(pd.DataFrame(d))
效果图:
4 PIL库
PIL(RGB)
Image 是 PIL 库中代表一个图像的类(对象)。
Image.open 方法打开的图片类型为PIL Image, 值为0-255,尺寸为 W * H * C。
通过img=np.array(img)转为numpy数组后,尺寸为 H * W * C。
(python版)OpenCV(BGR)
cv2.imread 方式打开的图片类型为np数组, 值为0-255,尺寸为 H * W * C。
代码:
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('test.jpg')
#img.show() #自动调用计算机上显示图片的工具
plt.imshow(img)
plt.show(img)
#获得图像的模式
print(img.mode)
width, height = img.size
print(width, height)
img_rotate = img.rotate(90)
plt.imshow(img_rotate)
plt.show(img_rotate)
# 图片剪切:左上角坐标+右下角坐标
img_crop = img.crop((200,0,340,130))
#保存图片
img_crop.save('crop_result.png')
#展示图片
plt.imshow(img_crop)
plt.show(img_crop)
# 图像缩放
img_resize = img.resize((int(width*0.3),int(height*0.3)), Image.ANTIALIAS)
plt.imshow(img_resize)
plt.show(img_resize)
#左右镜像
img_lr = img.transpose(Image.FLIP_LEFT_RIGHT)
plt.imshow(img_lr)
plt.show(img_lr)
#上下镜像
img_bt = img.transpose(Image.FLIP_TOP_BOTTOM)
plt.imshow(img_bt)
plt.show(img_bt)
pass
效果图:
5 Math库
代码:
import math
print(math.ceil(5.1)) #返回数字的上入整数
print(math.floor(4.8)) #返回数字的下舍整数
print(math.fabs(-1)) #返回数字的绝对值
print(math.sqrt(16)) #返回数字的平方根
print(math.exp(2)) #返回e的x次幂
效果图:
6 Matplotlib库
代码:
import matplotlib.pyplot as plt
import numpy as np
#等差数列
x = np.linspace(0, 10, 10)
y1 = x ** 2 + 1
y2 = x + 5
plt.figure(figsize=(10,5))
plt.plot(x, y1, color='red', linewidth=3)
plt.plot(x, y2, color='blue', linewidth=1)
plt.xlabel('x', fontsize=10)
plt.ylabel('y', fontsize=10)
dots_1 = np.random.rand(10) * 10
dots_2 = [100, 66, 2, 45, 10, 90, 55, 1, 30, 45]
#c表示颜色,alpha表示透明度
plt.scatter(dots_1, dots_2, c='green', alpha=0.8)
x1 = np.arange(10)
y3 = x ** 2
plt.bar(x1, y3, facecolor='#9999ff', edgecolor='white')
for ax, ay in zip(x1, y3):
plt.text(ax, ay, '%.1f' % ay, ha='center', va='bottom')
#显示图形
plt.show()
pass
结果图: