[关闭]
@chenwei123 2018-09-08T08:56:52.000000Z 字数 13313 阅读 769

Python 编程入门

Python


Python 可以做什么?
1.网站
2.爬虫
3.大数据处理
4.机器学习

python 的介绍

  1. "第一个参数:{},第二个参数:{},第三个参数:{}".format(a,b,c)
  1. max(1,2,3,4,5,6) #6
  2. min(1,2,3,4,5,6) #1
  3. sum([1,2,3,4,5,6]) #21
  4. divmod(10,3) #(3,1) 3是商,1是余数

Python数据库和爬虫

1.数据库管理软件: SequelPro
2.Python 数据结构: 可视化工具
3.MySQL数据类型
数据库分为关系数据库(mysql)和非关系数据库(mongodb,redis);非关系数据库json 格式存储.

1.mysql数据库的基本操作

  1. mysql -u root -p 链接数据库
  2. show database; 查看数据库
  3. use database_name; 选择数据库
  4. show tables; 查看数据库表
  5. desc table_name; 查看数据库表的结构
  6. select * from table_name; 查看数据库表中的数据
  7. select * from table_name limit number; 查看表中数据并限制个数
  8. create database database_name; 创建数据库
  9. drop database database_name; 删除数据库
  10. 重置密码(8.0)
  11. ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_password';
  12. 重置密码(以前的)
  13. SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_password')
  14. 1.创建数据库表
  15. 语法:
  16. CREATE TABLE `table_name` (column_name column_type);
  17. 实例:
  18. CREATE TABLE `user`(
  19. `id` INT UNSIGNED AUTO_INCREMENT,
  20. `name` VARCHAR(40),
  21. `sex` VARCHAR(10) NOT NULL,
  22. PRIMARY KEY(`id`)
  23. );
  24. 解析:
  25. 1.如果你不想字段为 NULL 可以设置字段的属性为 NOT NULL;
  26. 2.AUTO_INCREMENT为自增属性,一般用于主键,数值会自动加1;
  27. 3.PRIMARY KEY关键字用于定义主键字段;
  28. 2.表中插入数据
  29. 语法:
  30. INSERT INTO table_name (field1, field2,...) VALUES ( value1, value2,...);
  31. 实例:
  32. insert into user(name, sex) values ("小明", "男");
  33. 3.查询数据
  34. 语法:
  35. select * from table_name;
  36. 实例:
  37. select * from user;
  38. 4.删除数据库表
  39. drop table table_name

2. Python 操作数据库

  1. #pip3 install pymysql
  2. import pymysql
  3. DATABASE = {
  4. 'host':'127.0.0.1', #如果是远程数据库,则是远程数据库的ip 地址
  5. 'database':'student',
  6. 'user':'root',
  7. 'password':'root1234'
  8. }
  9. db = pymysql.connect(**DATABASE)
  10. cursor = db.cursor() #游标
  11. #插入数据
  12. sql = "insert into user (name, age) values ('小姚', '20');"
  13. cursor.execute(sql)
  14. db.commit()
  15. #更新数据
  16. sql = "update user set name='小可爱' where id=5;"
  17. cursor.execute(sql)
  18. db.commit()
  19. #查询数据
  20. sql = "select * from user;"
  21. cursor.execute(sql)
  22. results = cursor.fetchall()
  23. for row in results:
  24. print(row)
  25. #删除数据
  26. sql = "delete from user where name='小姚';"
  27. cursor.execute(sql)
  28. db.commit()

Numpy 的基本操作

数组跟列表的区别,列表可以存储任意类型的数据,数组只能放一种类型的。

中文文档链接
英文文档链接

1. numpy 的安装

pip3 install numpy

2. 列表转为数组

  1. import numpy as np
  2. a_list = list(range(10)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  3. a_arr = np.array(a_list) #array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  4. type(a_list) #<class 'list'>
  5. type(a_arr) #<class 'numpy.ndarray'>

3. 生成数组

  1. #1.一维数组
  2. import numpy as np
  3. a_zeros_arr=np.zeros(3) #生成一个3个元素的数组, array([0., 0., 0.])
  4. a.dtype #查看数组类型, dtype('float64')
  5. #指定数组类型
  6. a_zeros_arr = np.zeros(3, dtype=int) #array([0, 0, 0])
  7. #2.多维数组
  8. a_zeros_arr = np.zeros((2,2), dtype=int) #array([[0, 0],[0, 0]]) 值为0
  9. a_ones_arr = np.ones((2,2), dtype=int) #array([[1, 1],[1, 1]]) 值为1
  10. a_full_arr = np.full((2,2), 3) #array([[3, 3],[3, 3]]) 值为指定的任意值
  11. b_zeros_arr = np.zeros_like(a_zeros_arr) #array([[0, 0],[0, 0]])
  12. b_ones_arr = np.ones_like(a_ones_arr) #array([[1, 1],[1, 1]])
  13. b_full_arr = np.full_like(a_full_arr, 4) #array([[4, 4],[4, 4]])

4. 生成数组(随机数)

  1. random.random() #0~1之间的随机数 0<x<1
  2. random.randint(1,3) #1~3之间的数 1<=x<=3
  3. a_random_arr = np.random.random((2,2)) #array([[0.64581359, 0.75547149],[0.96443955, 0.69208698]]) 0<x<1
  4. a_randint_arr = np.random.randint(1,3, (2,2)) #array([[1, 1], [1, 2]]) 1<=x<3

5. 生成数组(范围取值)

  1. a_list = list(range(0,10, 2)) #[0, 2, 4, 6, 8]
  2. a_range_arr = np.arange(0, 10, 2) #array([0, 2, 4, 6, 8])
  3. a_lin_arr = np.linspace(1,3,5) #array([1. , 1.5, 2. , 2.5, 3. ])
  4. #n维的单位矩阵
  5. a_arr = np.eye(3)
  6. """
  7. array([[1., 0., 0.],
  8. [0., 1., 0.],
  9. [0., 0., 1.]])
  10. """

6. 访问数组中的元素

  1. a_list = [[1,2,3], [4,5,6]]
  2. b_arr = np.array(a_list)
  3. """
  4. array([[1, 2, 3],
  5. [4, 5, 6]])
  6. """
  7. b_arr[1][1] #5
  8. b_arr[1, 1] #5,等同于上面的访问方式
  9. b_arr[:2][:2] #先去前2个数组,在新数组基础上再取前两个
  10. """
  11. array([[1, 2, 3],
  12. [4, 5, 6]])
  13. """
  14. b_arr[:2, :2] #取出二维数组中的前俩个元素组成新的数组
  15. """
  16. array([[1, 2],
  17. [4, 5]])
  18. """

7. 数组的属性

  1. a_list = [[1,2,3], [4,5,6]]
  2. b_arr = np.array(a_list)
  3. """
  4. array([[1, 2, 3],
  5. [4, 5, 6]])
  6. """
  7. b_arr.ndim #维度 2
  8. b_arr.shape #形状 (2, 3)
  9. b_arr.size #个数 6
  10. b_arr.dtype #数组数据类型
  11. b_arr.itemsize #数组单个元素占内存的大小 8
  12. b_arr.nbytes #数组所有元素总的内存大小 48

8. 运算

  1. a_arr = np.array(list(range(10))) #array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  2. #加(+)、减(-)、乘(*)、除(/)、求余(%)、求商(//)、次方(**)、求反(-负数)
  3. 加法 a_arr+10 等同于 np.add(a_arr, 10)
  4. #array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
  5. 乘法 a_arr*10 等同于 np.multiply(a_arr, 10)
  6. #array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
  7. 减法 a_arr-10 等同于 np.subtract(a_arr, 10)
  8. #array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1])
  9. 除法 a_arr/10 等同于 np.divide(a_arr, 10)
  10. #array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
  11. 求余 a_arr%5 等同于 np.mod(a_arr, 5)
  12. #array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4])
  13. 求商 a_arr//2 等同于 np.floor_divide(a_arr, 2)
  14. #array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4])
  15. 次方 a_arr**2 等同于 np.power(a_arr, 2)
  16. #array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
  17. 求反 -a_arr 等同于 np.negative(a_arr)
  18. #array([ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9])
  19. b_arr = np.linspace(0, np.pi, 3)
  20. #array([0. , 1.57079633, 3.14159265])
  21. np.sin(b_arr)
  22. #array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])
操作符 等价函数 描述
+ np.add 加法
- np.subtract 减法
* np.multiply 乘法
/ np.divide 除法
% np.mod 求余
// np.floor_divide 求商
** np.power 次方
- np.negative 负数

9. 统计

  1. #求和
  2. #数组一维求和
  3. a = np.full(5, 1) #array([1, 1, 1, 1, 1])
  4. sum(a)
  5. np.sum(a) (推荐使用这种形式)
  6. #数组多维求和
  7. a = np.array([[1,2], [3,4]])
  8. """
  9. array([[1, 2],
  10. [3, 4]])
  11. """
  12. np.sum(a) #所有元素求和 10
  13. np.sum(a, axis=1) #按行求和 array([3, 7])
  14. np.sum(a, axis=0) #按列求和 array([4, 6])
  15. 同理,
  16. np.max(a)
  17. np.max(a, axis=1)
  18. np.max(a, axis=0)

10. 比较

  1. a = np.array(range(5)) #array([0, 1, 2, 3, 4])
  2. a > 3 #array([False, False, False, False, True])
  3. a != 3 #array([ True, True, True, False, True])
  4. a == a #array([ True, True, True, True, True])
  5. np.all(a>1) #False, 所有数都大于1
  6. np.any(a>1) #True, 至少一个大于1
操作符 等价函数
== np.equal
!= np.not_equal
< np.less
> np.greater
<= np.less_equal
>= np.greater_equal

11. 变形

  1. a = np.full((3,4), 3)
  2. #注意,reshape变形之后的总个数要等于变形之前的
  3. a.reshape(4,3)
  4. a.reshape(2,6)
  5. """
  6. array([[3, 3, 3, 3, 3, 3],
  7. [3, 3, 3, 3, 3, 3]])
  8. """

12. 排序

  1. li = [[1,2,3], [31,12,4], [32, 2, 33]]
  2. a = np.array(li)
  3. """
  4. array([[ 1, 2, 3],
  5. [31, 12, 4],
  6. [32, 2, 33]])
  7. """
  8. np.sort(a) #按行排序, a不变
  9. a.sort() #默认按行排序, a 变
  10. """
  11. array([[ 1, 2, 3],
  12. [ 4, 12, 31],
  13. [ 2, 32, 33]])
  14. """
  15. a.sort(axis=0) #按列排序, a变
  16. """
  17. array([[ 1, 2, 3],
  18. [ 2, 12, 31],
  19. [ 4, 32, 33]])
  20. """

13. 拼接

  1. a = np.array([1,2,3])
  2. b = np.array([0,2,4], [1,3,5])
  3. """
  4. array([[0, 2, 4],
  5. [1, 3, 5]])
  6. """
  7. np.concatenate([b,b], axis=0) #按行拼接
  8. """
  9. array([[0, 2, 4],
  10. [1, 3, 5],
  11. [0, 2, 4],
  12. [1, 3, 5]])
  13. """
  14. np.concatenate([b,b], axis=1) #按列拼接
  15. """
  16. array([[0, 2, 4, 0, 2, 4],
  17. [1, 3, 5, 1, 3, 5]])
  18. """

14. random 讲解

  1. 1. np.random.rand() #生成(0,1)之间的一个数
  2. 2. np.random.rand(5) #生成5个元素的数组,随机取值(0,1)
  3. """
  4. array([0.79607008, 0.81415032, 0.51516127, 0.29400689, 0.10346322])
  5. """
  6. 3. np.random.rand(5,4) #生成5行4列的数组,随机取值(0,1)
  7. """
  8. array([[0.11204402, 0.56018237, 0.29255916, 0.3400223 ],
  9. [0.6379297 , 0.73085658, 0.92353737, 0.43426313],
  10. [0.89570646, 0.44098276, 0.80479348, 0.91783251],
  11. [0.18535441, 0.62034598, 0.17123969, 0.21449212],
  12. [0.16348938, 0.86119781, 0.11963413, 0.07361377]])
  13. """
  14. 4. np.random.random() #生成(0,1)之间的一个数
  15. 5. np.random.random(5) #生成5个元素的数组,随机取值(0,1)
  16. """
  17. array([0.28560097, 0.62186389, 0.999904 , 0.12896292, 0.36700434])
  18. """
  19. 6. np.random.random((5,4)) #生成5行4列的数组,随机取值(0,1)
  20. """
  21. array([[0.0796853 , 0.20823343, 0.81220792, 0.03378476],
  22. [0.05286695, 0.39902488, 0.33382217, 0.31498118],
  23. [0.28531483, 0.76593973, 0.81974177, 0.46401695],
  24. [0.28562308, 0.79488005, 0.29246923, 0.63715793],
  25. [0.47336978, 0.69501443, 0.11519155, 0.07043233]])
  26. """
  27. 7. np.random.randint(3) #生成[0,3)之间的一个整数
  28. 8. np.random.randint(1,3) #生成[1,3)之间的一个整数
  29. 9. np.random.randint(1,3, (2,2)) #生成两行两列的数组,随机取值[1,3)之间的整数
  30. """
  31. array([[2, 2],
  32. [1, 1]])
  33. """

15. cumsum用法

  1. b=np.array([[1,2,3],[4,5,6]])
  2. """
  3. array([[1, 2, 3],
  4. [4, 5, 6]])
  5. """
  6. b.cumsum()
  7. """
  8. 当前位置元素值等于它与前面(先行后列)的所有数相加
  9. array([ 1, 3, 6, 10, 15, 21])
  10. """
  11. b.cumsum(0)
  12. """
  13. 当前位置元素值等于它与前面(列)的所有数相加
  14. array([[1, 2, 3],
  15. [5, 7, 9]])
  16. """
  17. b.cumsum(1)
  18. """
  19. 当前位置元素值等于它与前面(行)的所有数相加
  20. array([[ 1, 3, 6],
  21. [ 4, 9, 15]])
  22. """

Pandas

1. Pandas基本操作

索引 id name age 数学 语文
0 1 小明 20 90 78
1 2 小兰 10 70 23
2 3 小花 30 80 89
3 4 小李 18 66 65
4 5 小可爱 20 97 93
5 6 小命名 20 78 90

pandas中的 dataframe的操作,很大一部分跟 numpy中的二维数组操作是近似的.

1. 基本使用
  1. import pandas as pd
  2. df = pd.read_csv("/Users/chen/Desktop/user.csv")
  3. df.tail(2) #取后2行,默认是5
  4. df.head(2) #取前2行,默认是5
  5. """
  6. id name age 数学 语文
  7. 0 1 小明 20 90 78
  8. 1 2 小兰 10 70 23
  9. """
  10. type(df) #<class 'pandas.core.frame.DataFrame'>
  11. df.columns #列名 Index(['id', 'name', 'age', '数学', '语文'], dtype='object')
  12. df.index #索引 (stop 代表共有几行) RangeIndex(start=0, stop=6, step=1)
2.条件筛选
  1. df.数学 > 80 #判断所有的数学成绩是否大于80
  2. """
  3. 0 True
  4. 1 False
  5. 2 False
  6. 3 False
  7. 4 True
  8. 5 False
  9. """
  10. df[df.数学 > 80] #筛选出数学成绩大于80的
  11. """
  12. id name age 数学 语文
  13. 0 1 小明 20 90 78
  14. 4 5 小可爱 20 97 93
  15. """
  16. df[(df.数学>80) & (df.语文>80)] #复杂筛选(多重条件)
  17. """
  18. id name age 数学 语文
  19. 4 5 小可爱 20 97 93
  20. """
3.排序
  1. df.sort_values(["age", "数学"]).head() #排序,先按 age,然后在数学,升序, 最后取前5行
4.访问
  1. df.loc[0] #访问第0行, 按照索引去访问的
  2. df.iloc[0] #实实在在的第几行,像列表访问一样的原理
  3. df.ix[0] #loc,iloc 融合,数字索引存在,则按索引访问,不存在则按 iloc 形式访问
  4. df.ix[:2] #访问前两行
  5. df[0] #访问某行,是错误的
  6. df[0:2] #访问多行数据是可以用切片的
  7. """
  8. id name age 数学 语文
  9. 0 1 小明 20 90 78
  10. 1 2 小兰 10 70 23
  11. """
5.创建表dataframe
  1. dic = {
  2. "数学":[70,80,70],
  3. "语文":[78,86,96],
  4. "name":["小一", "小二", "小三"]
  5. }
  6. df2 = pd.DataFrame(dic) #可以指定索引pd.DataFrame(dic, index=["one", "two", "three])
  7. """
  8. 数学 语文 name
  9. 0 70 78 小一
  10. 1 80 86 小二
  11. 2 70 96 小三
  12. """
6.dataframe 中的数组(values 用法)
  1. df.values #访问所有的数据,返回的是数组
  2. """
  3. array([[1, '小明', 20, 90, 78],
  4. [2, '小兰', 10, 70, 23],
  5. [3, '小花', 30, 80, 89],
  6. [4, '小李', 18, 66, 65],
  7. [5, '小可爱', 20, 97, 93],
  8. [6, '小命名', 20, 78, 90]], dtype=object)
  9. """
  10. df.数学.values #dataframe 中的数组
  11. """
  12. array([90, 70, 80, 66, 97, 78])
  13. """
  14. df.数学.value_counts() #简单的统计,对应分数共有几人
  15. """
  16. 78 1
  17. 70 1
  18. 66 1
  19. 90 1
  20. 97 1
  21. 80 1
  22. Name: 数学, dtype: int64
  23. """
7.提取多列,单列
  1. df.数学 df["数学"] #提取单列
  2. df[["数学", "语文"]].head(2) #提取多列
  3. """
  4. 数学 语文
  5. 0 90 78
  6. 1 70 23
  7. """
  8. a = df[["数学", "name"]].head(2)
  9. a*2 #对应字段是数字的话,则乘2,字符串的话,则拼接
  10. """
  11. 数学 name
  12. 0 180 小明小明
  13. 1 140 小兰小兰
  14. """
8.增加新列和删除列(重点)
1. map 用法
  1. def func(score):
  2. if score >= 80:
  3. return "优秀"
  4. elif score >= 70:
  5. return "良"
  6. elif score >= 60:
  7. return "及格"
  8. else:
  9. return "差"
  10. df["数学等级"] = df.数学.map(func)
  11. df
  12. """
  13. id name age 数学 语文 数学等级
  14. 0 1 小明 20 90 78 优秀
  15. 1 2 小兰 10 70 23 良
  16. 2 3 小花 30 80 89 优秀
  17. 3 4 小李 18 66 65 及格
  18. 4 5 小可爱 20 97 93 优秀
  19. 5 6 小命名 20 78 90 良
  20. """
2.applymap 用法
  1. #applymap 是对 dataframe中所有数据进行操作的一个函数,非常重要
  2. df func(number):
  3. return number + 10
  4. 等价于
  5. func = lambda number:number+10
  6. df.applymap(lambda number:str(number)+" -").head(2)
  7. """
  8. id name age 数学 语文 数学等级
  9. 0 1 - 小明 - 20 - 90 - 78 - 优秀 -
  10. 1 2 - 小兰 - 10 - 70 - 23 - 良 -
  11. """
3.apply 用法
  1. #根据多列生成新列的操作, apply
  2. df["score"] = df.apply(lambda x:x.数学+x.语文, axis=1) #x 代表dataframe
  3. """
  4. id name age 数学 语文 数学等级 score
  5. 0 1 小明 20 90 78 优秀 168
  6. 1 2 小兰 10 70 23 良 93
  7. 2 3 小花 30 80 89 优秀 169
  8. 3 4 小李 18 66 65 及格 131
  9. 4 5 小可爱 20 97 93 优秀 190
  10. 5 6 小命名 20 78 90 良 168
  11. """
4.删除列
  1. df.drop(["score"], axis=1)
  2. """
  3. id name age 数学 语文 数学等级
  4. 0 1 小明 20 90 78 优秀
  5. 1 2 小兰 10 70 23 良
  6. 2 3 小花 30 80 89 优秀
  7. 3 4 小李 18 66 65 及格
  8. 4 5 小可爱 20 97 93 优秀
  9. 5 6 小命名 20 78 90 良
  10. """

2. Pandas绘图

matplotlib.pylot的文档
pandas.DataFrame 文档

  1. import pandas as pd
  2. import matplotlib
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. #%matplotlib inline
  6. #上一行必不可少(notebook中可以直接在命令行中运行显示效果图的,可以注释掉)
  7. plt.show() #用来展示图片
1. matplotlib.pyplot 绘制图形
1. plot()subplot()legend()scatter()用法
  1. plt.plot(x, y, [format], color='gray', markersize=15, linewidth=4, markerfacecolor='white', markeredgecolor='gray', markeredgewidth=2, label='图形1')
  2. """
  3. format:图形的样式('-p', 'o', '--')
  4. color: 图形的颜色(坐标点和连线)
  5. markersize:坐标点的大小
  6. linewidth: 点之间连线的宽度
  7. markerfacecolor:坐标点的填充颜色
  8. markeredgecolor:坐标点的边框颜色
  9. markeredgewidth:坐标点的边框线宽
  10. label: 图形的标签
  11. 详情请看:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
  12. """
  13. plt.subplot(row, column, index, facecolor='yellow')
  14. """
  15. row: 行数
  16. column: 列数
  17. index: 在第几个单元格绘制图形
  18. facecolor: 坐标系的填充色
  19. """
  20. plt.legend(loc=0) legend 控制 label 的显示效果,loc 是控制 label 位置,不填默认最好
  21. """
  22. 0:'best'
  23. 1:'upper right'(右上)
  24. 2:'upper left'(左上)
  25. 3:'lower left'(左下)
  26. 4:'lower right'(右下)
  27. 5:'right'(中右)
  28. 6:'center left'(中左)
  29. 7:'center right'(中右)
  30. 8:'lower center(中下)
  31. 9:'upper center'(中上)
  32. 10:'center'(中间)
  33. """
  34. plt.scatter(x, y, s=50, c='gray', marker='o', alpha=0.4)
  35. """
  36. s:坐标点大小
  37. c:坐标点颜色
  38. marker:坐标点样式, 更多参考:https://matplotlib.org/api/markers_api.html#module-matplotlib.markers
  39. alpha:坐标点颜色透明度
  40. """
2. 绘制多个图形
  1. x = np.linspace(0, 10, 20)
  2. plt.subplot(2,2,1)
  3. plt.plot(x, np.sin(x), label='p1')
  4. plt.legend(loc=4)
  5. plt.subplot(2,2,2, facecolor='yellow')
  6. plt.plot(x, np.sin(x), '--', markersize=15, linewidth=4, markerfacecolor='white', markeredgecolor='red', markeredgewidth=2, label='p2')
  7. plt.legend(loc=4)
  8. plt.subplot(2,2,3)
  9. plt.plot(x, np.sin(x), '-o', color='green', markersize=5, linewidth=4, markerfacecolor='white', markeredgecolor='red', markeredgewidth=2, label='p3')
  10. plt.legend(loc=4)
  11. plt.subplot(2,2,4)
  12. plt.plot(x, np.sin(x), '-p', color='gray', markersize=10, linewidth=4, markerfacecolor='white', markeredgecolor='red', markeredgewidth=2, label='p4')
  13. plt.legend(loc=4)
  14. plt.show()

图1

3. 单个图形绘制多条线
  1. x=np.linspace(0, 7, 20)
  2. plt.plot(x, np.sin(x), '-o', label='p1')
  3. plt.plot(x, np.cos(x), '--', label='p2')
  4. plt.plot(range(6), range(6), '-p', label='p3')
  5. plt.legend()
  6. plt.show()

图2

4. ylimxlim 限定范围绘制图
  1. #ylim、xlim限定范围
  2. x=np.linspace(0, 7, 20)
  3. plt.plot(x, np.sin(x), '-p')
  4. plt.ylim(-0.5, 1)
  5. plt.xlim(0, 5)
  6. plt.show()

图3

5. 绘制散点图
  1. plt.style.use('classic') #设置主题样式, classic经典样式
  2. x = np.random.randn(100)
  3. y = np.random.randn(100)
  4. colors = np.random.rand(100) #0~1之间取值, 生成100个元素的一维数组
  5. sizes = 1000 * np.random.rand(100)
  6. plt.scatter(x, y, s=sizes, c=colors, alpha=0.4)
  7. plt.colorbar()
  8. plt.show()

未设经典样式和颜色条,见图4
未设经典样式,见图5
设经典样式和颜色条,见图6
图4
图5
图6

6. 保存绘制的图片
  1. fig = plt.figure()
  2. x=np.linspace(0, 7, 20)
  3. plt.plot(x, np.sin(x), '-o', label='p1')
  4. plt.legend()
  5. fig.savefig("/Users/chen/Desktop/python3/project/project1/0-0.png")
2. pandas本身自带制图
1. 线形图
  1. df = pd.DataFrame(np.random.rand(100, 4).cumsum(0), columns=['A','B','C','D'])
  2. df.plot() #整个数组
  3. df.A.plot() #某一列
  4. plt.show()

图7
图8

2. 柱状图📊
  1. df = pd.DataFrame(np.random.randint(10, 50, (3,4)), columns=['A', 'B', 'C', 'D'], index=["one", "two", "three"])
  2. df.plot(kind='bar', stacked=True) #stacked 叠加
  3. df.plot.bar() #整个数组 df.plot.bar() <===> df.plot(kind='bar')
  4. df.A.plot.bar() #某一列
  5. plt.show()

图9
图10

3. 直方图
  1. df = pd.DataFrame(np.random.randn(100, 4), columns=['A','B','C','D'])
  2. df.hist()
  3. df.hist(column='A', grid=False) #grid:图形的背景网格
  4. plt.show()

图11
图12

4. 密度图
  1. df = pd.DataFrame(np.random.randn(100, 4), columns=['A','B','C','D'])
  2. df.plot.kde()
  3. plt.show()

图13


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注