一、Numpy列表简单介绍
1、numpy其实就是多维的数组对象
import numpy as np
data = [1, 2, 3, 4]
n = np.array(data)
print(data)
print(n)
print(n.shape)
print(n.dtype)
2、嵌套序列:是有一组等长列表组成的列表
arr = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
arr2 = np.array(arr)
print(arr)
print(arr2)
print(arr2.shape)
3、numpy会对数据类型进行推理
arr = [['1', '2', 3, 4], ['5', 6, 7, 8]]
arr2 = np.array(arr)
print(arr)
print(arr2)
print(arr2.dtype)
arr = [[1.21, 2.12, 3, 4], [1, 2, 3, 4]]
arr2 = np.array(arr)
print(arr)
print(arr2)
print(arr2.dtype)
4、指定长度的数组的快速创建
np.zeros([2, 3])
np.zeros([2, 3, 4])
np.ones([2, 3])
np.empty((3, 3))
np.arange(10)
5、类型转换
arr = np.array([1, 2, 1, 3, 1,4, -2.1, -2.2, -3.3])
print(arr)
print(arr.astype(np.int32))
6、矢量化 -- 进行数据的批量运算和处理
# 加法:维度相等
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([11, 22, 33, 44])
arr1 + arr2
arr1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
arr2 = np.array([[11, 22, 33, 44], [55, 66, 77, 88]])
print(arr1 + arr2)
# 乘法
arr1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
arr2 = np.array([[11, 22, 33, 44], [55, 66, 77, 88]])
print(arr1 * arr2)
7、索引和切片操作
arr = np.arange(10)
print(arr)
arr[2:4]
aa = arr.copy()
print(aa)
aa[2]
aa[2] = 22
aa
aa[6:] = 666
aa
arr1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
arr1[1][0:]
8、numpy array的比较运算
names = np.array(['张三','李四','王五'])
names == '张三'
# 关系运算 & 、|
(names == '张三') & (names == '李三')
9、花式索引 fancy indexing numpy中的一个术语,指的是利用整数数组来进行索引
arr = np.empty((8, 4))
for i in range(len(arr)):
arr[i] = i
print(arr)
print(arr[[3, 4, 0, 1]])
arr = np.arange(32).reshape((8, 4))
print(arr)
arr[[1, 5, 7, 2]]
arr[[1, 5, 7, 2], [0, 3, 2, 1]]
# 切片取整行/列 与数组索引不同,`:`表示所有
arr[[1, 5, 7, 2]][:,[0, 3, 2, 1]]
arr[[1, 5, 7, 2]][[0, 1, 2, 3],[0, 3, 2, 1]]
arr[[1, 5, 7, 2]][1:3,[0, 3, 2, 1]]
arr[[1, 5, 7, 2]][[3,2,1,0],:]
arr[[1, 5, 7, 2]][[3,2,1,0],0:3]
10、数组转置
arr = np.arange(15).reshape(3, 5)
print(arr)
arr.T
arr.transpose()
11、轴转置
arr = np.arange(24).reshape(2,3,4)
print(arr)
a = arr.transpose((1, 2, 0))
print(a)
# matplotlib
points = np.arange(-5, 5, 0.01)
xs, ys = np.meshgrid(points, points)
# print(xs)
# print(ys)
import matplotlib.pyplot as plt
z = np.sqrt(xs ** 2 + ys ** 2)
# print(z)
plt.imshow(z, cmap=plt.cm.spring)
plt.colorbar()
12、条件逻辑转数组
x_arr = np.array([1.1, 1.2, 1.3])
y_arr = np.array([2.1, 2.2, 2.3])
condition = np.array([True, False, True])
# zip 接受的参数是可迭代对象
# zip 函数用于将可迭代的对象作为参数,将对象中的元素打包成一个个元组,然后返回由这些元组组成的列表
l = zip(x_arr, y_arr, condition)
result = [x if z else y for x, y, z in l]
print(result)
np.where(condition, x_arr, y_arr)
13、值替换
arr = np.random.randn(4, 4)
print(arr)
arr = np.random.randn(4, 4)
print(arr)
arr_1 = np.where(arr>0, 5, -5)
print(arr_1)
arr = np.random.randn(4, 4)
print(arr)
arr_1 = np.where(arr>0, 5, arr)
print(arr_1)
14、numpy简单的数学运算
arr = np.arange(8).reshape(2,4)
print(arr)
arr.mean()
arr.sum()
arr.mean(axis=0) # 列
arr.mean(axis=1) # 行
arr.sum(axis=0) # 列
arr.sum(axis=1) # 行
# 排序
arr = np.array([9,8,7,6,5,4,3,2,1]).reshape(3, 3)
print(arr)
arr.sort()
print(arr)
position = 0
walk = [position]
steps = 1000
for i in range(steps):
step = 1 if np.random.randint(0,2) else -1
position += step
walk.append(position)
a = plt.plot(walk)
a
(np.abs(walk) == 10).argmax()
二、常用画图工具
1、matplotlib画图
官网:https://matplotlib.org/gallery/index.html
# 示例 1:
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3', 'G4', 'G5', 'G6']
men_means = [20, 34, 30, 35, 27, 10]
women_means = [25, 32, 34, 20, 25, 12]
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
# 示例 2:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
recipe = ["375 g flour",
"75 g sugar",
"250 g butter",
"200 g berries",
"100 g test"]
data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]
def func(pct, allvals):
absolute = int(pct/100.*np.sum(allvals))
return "{:.1f}%\n({:d} g)".format(pct, absolute)
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))
ax.legend(wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=8, weight="bold")
ax.set_title("Matplotlib bakery: A pie")
plt.show()
2、echarts画图
官网:https://matplotlib.org/gallery/index.html
pyecharts官网:https://pyecharts.org/#/zh-cn/quickstart?id=%e5%a6%82%e4%bd%95%e5%ae%89%e8%a3%85
# -*- coding:utf-8 -*-
__author__ = 'hope'
__date__ = '2020-05-06'
from pyecharts.charts import Bar
def test_bar_1():
bar = Bar()
bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,如 bar.render("mycharts.html")
bar.render()
def test_bar_2():
bar = (
Bar()
.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
.add_yaxis("商家X", [5, 20, 36, 10, 75, 90])
)
bar.render()
if __name__ == '__main__':
# test
# test_bar_1()
test_bar_2()
3、Axure画图
产品经理设计时常用;