numpy模块

numpy模块可以用来做数据分析, 对numpy数组(既有行既有列) -- 矩阵 进行科学运算

  1. import numpy as np
  2. # 用array方法将列表转换为np数组
  3. arr1 = np.array([1, 2, 3])
  4. arr2 = np.array([4, 5, 6])
  5. print(arr1) # [1 2 3]
  6. print(arr1 * arr2) # [ 4 10 18]

创建numpy数组

  1. # 一维数组
  2. arr1 = np.array([1, 2, 3])
  3. print(type(arr1), arr1) # <class 'numpy.ndarray'> [1 2 3]
  4. # 二维数组
  5. arr2 = np.array([
  6. [1, 2, 3],
  7. [4, 5, 6]
  8. ])
  9. print(arr2)
  10. # [[1 2 3]
  11. # [4 5 6]]
  12. # 三维数组
  13. arr3 = np.array([
  14. [[1, 2, 3],
  15. [4, 5, 6]],
  16. [[7, 8, 9],
  17. [10, 11, 12]]
  18. ])
  19. print(arr3)
  20. '''
  21. [[[ 1 2 3]
  22. [ 4 5 6]]
  23. [[ 7 8 9]
  24. [10 11 12]]]
  25. '''
  26. # 同过函数创建numpy数组
  27. print(np.ones((2, 3))) # 创建一个2行3列, 值都为1.的数组
  28. print(np.zeros((2, 3)))

numpy数组的属性和用法

  1. arr = np.array([
  2. [1, 2, 3],
  3. [4, 5, 6]
  4. ])
  5. # T 数组的转置 (高维数组) ---> 行列互换
  6. print(arr.T)
  7. '''
  8. [[1 4]
  9. [2 5]
  10. [3 6]]
  11. '''
  12. # dtype 数组元素的数据类型
  13. print(arr.dtype) # int32
  14. # size 数组元素个数
  15. print(arr.size) # 6
  16. # ndim 数组的维度
  17. print(arr.ndim) # 2
  18. # shape 数组的维度长度(以元祖形式)
  19. print(arr.shape[0]) # 2 0表示行
  20. print(arr.shape[1]) # 3 1表示列
  21. # astype 类型转换
  22. arr = arr.astype(np.float64)
  23. print(arr)
  24. '''
  25. [[1. 2. 3.]
  26. [4. 5. 6.]]
  27. '''
  28. # 索引取值,切片和修改值
  29. print(arr[:, :]) # 打印所有行所有列
  30. print(arr[0,0]) # 打印数组坐标为(1,1)的元素
  31. print(arr[0, :] # 打印打印第一行
  32. # 逻辑取值
  33. print(arr[arr > 4]) # [5. 6.]
  34. # hstack & vstack 数组的合并
  35. arr1 = np.array([
  36. [1, 2, 3],
  37. [4, 5, 6]
  38. ])
  39. arr2 = np.array([
  40. ['a', 'b', 'c'],
  41. ['d', 'e', 'f']
  42. ])
  43. print(np.hstack((arr1, arr2))) # 拼接行 括号内只能放一个元祖(arr1, arr2)
  44. print(np.vstack((arr1, arr2))) # 拼接列
  45. print(np.concatenate((arr1, arr2), axis=1)) # 默认以列合并 # 0表示列,1表示行
  46. # arange 范围
  47. print(np.arange(2, 10) # [2 3 4 5 6 7 8 9]
  48. # resharpe 重构形状
  49. print(arr1.reshape((3, 2))) # 3行2列
  50. '''
  51. [[1 2]
  52. [3 4]
  53. [5 6]]
  54. '''
  55. # numpy数组的运算
  56. arr1 = np.ones((3,4)) * 4
  57. print(arr1)
  58. print(np.sin(arr1))
  59. # 矩阵运算--点乘
  60. arr1 = np.array([
  61. [1, 2, 3],
  62. [4, 5, 6]
  63. ])
  64. arr2 = np.array([
  65. [1, 2],
  66. [3, 4],
  67. [5, 6]
  68. ])
  69. # 2*3 3*2 --> 2*2
  70. print(np.dot(arr1, arr2))
  71. '''
  72. [[22 28]
  73. [49 64]]
  74. '''
  75. # numpy.random生成随机数
  76. print(np.random.rand(3, 4))
  77. print(np.random.random((3, 4)))
  78. # np.random.seed(1)
  79. print(np.random.random((3, 4)))
  80. s = np.random.RandomState(1)
  81. print(s.random((3, 4)))
  82. arr = np.array([[1, 2, 3], [4, 5, 6], [9, 8, 9]])
  83. np.random.shuffle(arr)
  84. print(arr)
  85. # 针对一维
  86. print(np.random.choice([1, 2, 3], 1))
  87. # 针对某一个范围
  88. print(np.random.randint(1, 100, (3, 4)))

matplotlib模块

matplotlib模块可以用来画图

条形图

  1. from matplotlib import pyplot as plt # 约定俗称
  2. from matplotlib.font_manager import FontProperties # 修改字体
  3. font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
  4. plt.style.use('ggplot') # 设置背景
  5. class_ = ['三班', '四班', '五班', '六班']
  6. students = [30, 40, 50, 60]
  7. class_index = range(len(class_))
  8. plt.bar(class_index, students, color='y')
  9. plt.xlabel('班级', fontproperties=font)
  10. plt.ylabel('学生人数', fontproperties=font)
  11. plt.title('班级-学生人数', fontproperties=font, fontsize=28, fontweight=30)
  12. plt.xticks(class_index, class_, fontproperties=font)
  13. plt.show()

直方图

  1. import numpy as np
  2. from matplotlib import pyplot as plt
  3. from matplotlib.font_manager import FontProperties
  4. font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
  5. plt.style.use('ggplot')
  6. x1 = np.random.randn(10000)
  7. x2 = np.random.randn(10000)
  8. fig = plt.figure() # 生成一张画布
  9. ax1 = fig.add_subplot(1, 2, 1) # 1行2列第一个
  10. ax2 = fig.add_subplot(1, 2, 2)
  11. ax1.hist(x1, bins=50, color='b')
  12. ax2.hist(x2, bins=50, color='y')
  13. fig.suptitle('两个正太分布', fontproperties=font, fontsize=20)
  14. ax1.set_title('x1的正太分布', fontproperties=font)
  15. ax2.set_title('x2的正太分布', fontproperties=font)
  16. plt.show()

折线图

  1. import numpy as np
  2. from matplotlib import pyplot as plt
  3. from matplotlib.font_manager import FontProperties
  4. font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
  5. plt.style.use('ggplot')
  6. np.random.seed(1)
  7. x1 = np.random.randn(40).cumsum()
  8. x2 = np.random.randn(40).cumsum()
  9. x3 = np.random.randn(40).cumsum()
  10. x4 = np.random.randn(40).cumsum()
  11. plt.plot(x1, c='r', linestyle='-', marker='o', label='红圆线')
  12. plt.plot(x2, c='y', linestyle='--', marker='*', label='黄虚线')
  13. plt.plot(x3, c='b', linestyle='-.', marker='s', label='蓝方线')
  14. plt.plot(x4, c='g', linestyle=':', marker='s', label='绿方线')
  15. plt.legend(loc='best', prop=font) # 显示label
  16. plt.show()

散点图 + 直线图

  1. import numpy as np
  2. from matplotlib import pyplot as plt # 约定俗成
  3. from matplotlib.font_manager import FontProperties # 修改字体
  4. font = FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
  5. plt.style.use('ggplot')
  6. fig = plt.figure()
  7. ax1 = fig.add_subplot(1, 2, 1)
  8. ax2 = fig.add_subplot(1, 2, 2)
  9. x = np.arange(20)
  10. y = x ** 2
  11. x2 = np.arange(20)
  12. y2 = x2
  13. ax1.scatter(x, y, c='r', label='红')
  14. ax2.scatter(x2, y2, c='b', label='蓝')
  15. ax2.plot(x, y)
  16. ax2.plot(x2, y2)
  17. fig.suptitle('两张图', fontproperties=font, fontsize=15)
  18. ax1.set_title('散点图', fontproperties=font)
  19. ax2.set_title('折线图', fontproperties=font)
  20. ax1.legend(prop=font)
  21. plt.show()

pandas模块

pandas模块可以用来操作excel/json/sql/ini/csv(配置文件)/等

  1. import pandas as pd
  2. import numpy as np
  3. np.random.seed(1)
  4. index = pd.date_range('2019-01-01', periods=6, freq='M')
  5. columns = ['c1', 'c2', 'c3', 'c4']
  6. val = np.random.randn(6, 4)
  7. df = pd.DataFrame(index=index, columns=columns, data=val)
  8. print(df)
  9. '''
  10. c1 c2 c3 c4
  11. 2019-01-31 1.624345 -0.611756 -0.528172 -1.072969
  12. 2019-02-28 0.865408 -2.301539 1.744812 -0.761207
  13. 2019-03-31 0.319039 -0.249370 1.462108 -2.060141
  14. 2019-04-30 -0.322417 -0.384054 1.133769 -1.099891
  15. 2019-05-31 -0.172428 -0.877858 0.042214 0.582815
  16. 2019-06-30 -1.100619 1.144724 0.901591 0.502494
  17. '''
  18. # 保存文件
  19. df.to_excel('date_c.xlsx')
  20. # 读出文件
  21. df = pd.read_excel('date_c.xlsx', index_col=[0])
  22. print(df)
  23. print(df.index)
  24. '''
  25. DatetimeIndex(['2019-01-31', '2019-02-28', '2019-03-31', '2019-04-30',
  26. '2019-05-31', '2019-06-30'],
  27. dtype='datetime64[ns]', freq=None)
  28. '''
  29. print(df.columns) # Index(['c1', 'c2', 'c3', 'c4'], dtype='object')
  30. print(df.values)
  31. '''
  32. [[ 1.62434536 -0.61175641 -0.52817175 -1.07296862]
  33. [ 0.86540763 -2.3015387 1.74481176 -0.7612069 ]
  34. [ 0.3190391 -0.24937038 1.46210794 -2.06014071]
  35. [-0.3224172 -0.38405435 1.13376944 -1.09989127]
  36. [-0.17242821 -0.87785842 0.04221375 0.58281521]
  37. [-1.10061918 1.14472371 0.90159072 0.50249434]]
  38. '''
  39. print(df[['c1', 'c2']]) # 按列
  40. '''
  41. c1 c2
  42. 2019-01-31 1.624345 -0.611756
  43. 2019-02-28 0.865408 -2.301539
  44. 2019-03-31 0.319039 -0.249370
  45. 2019-04-30 -0.322417 -0.384054
  46. 2019-05-31 -0.172428 -0.877858
  47. 2019-06-30 -1.100619 1.144724
  48. '''
  49. # 按index取值
  50. print(df.loc['2019-01-31'])
  51. print(df.loc['2019-01-31':'2019-05-31']) # 按行
  52. # 按照values取值
  53. print(df)
  54. print(df.iloc[0, 0]) # 第一个值
  55. df.iloc[0, :] = 0 # 让第一行都为0
  56. print(df)

Python3 常用模块3的更多相关文章

  1. python3 常用模块详解

    这里是python3的一些常用模块的用法详解,大家可以在这里找到它们. Python3 循环语句 python中模块sys与os的一些常用方法 Python3字符串 详解 Python3之时间模块详述 ...

  2. python3 常用模块

    一.time与datetime模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们 ...

  3. Python3常用模块的安装

    1.mysql驱动:mysql-connector-python 1.安装 $ pip3 install mysql-connector-python --allow-external mysql-c ...

  4. Python3 常用模块2

    目录 time 模块 时间戳形式 格式化时间 结构化时间 time.time() time.sleep() datetime 模块 random 模块 hashlib 模块 和 hmac 模块 typ ...

  5. Python3 常用模块1

    目录 os模块 对文件夹操作 对文件进行操作 sys模块 json 和pickle模块 logging模块 日志等级 longging模块的四大组件 自定义配置 os模块 通过os模块我们可以与操作系 ...

  6. Python3基础(5)常用模块:time、datetime、random、os、sys、shutil、shelve、xml处理、ConfigParser、hashlib、re

    ---------------个人学习笔记--------------- ----------------本文作者吴疆-------------- ------点击此处链接至博客园原文------ 1 ...

  7. Python3基础笔记--常用模块

    目录: 参考博客:Python 之路 Day5 - 常用模块学习 Py西游攻关之模块 一.time模块 二.random模块 三.os模块 四.sys模块 五.hashlib模块 六.logging模 ...

  8. day--6_python常用模块

    常用模块: time和datetime shutil模块 radom string shelve模块 xml处理 configparser处理 hashlib subprocess logging模块 ...

  9. python基础之常用模块以及格式化输出

    模块简介 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要 ...

随机推荐

  1. netty源码解析(4.0)-29 Future模式的实现

    Future模式是一个重要的异步并发模式,在JDK有实现.但JDK实现的Future模式功能比较简单,使用起来比较复杂.Netty在JDK Future基础上,加强了Future的能力,具体体现在: ...

  2. 我的第一个 60 k+ Star Java开源项目

    JavaGuide([Java学习+面试指南] 一份涵盖大部分Java程序员所需要掌握的核心知识):https://github.com/Snailclimb/JavaGuide. 人生总有各种各样的 ...

  3. oracle实现"limit"功能

    转载于http://blog.sina.com.cn/s/blog_67e2758d0100s3oc.html oracle数据库不支持mysql中limit功能,但可以通过rownum来限制返回的结 ...

  4. 剑指Offer-23.二叉搜索树的后序遍历序列(C++/Java)

    题目: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则输出Yes,否则输出No.假设输入的数组的任意两个数字都互不相同. 分析: 二叉树的后序遍历也就是先访问左子树,再访问右 ...

  5. Python 编程语言要掌握的技能之一:善用变量来改善代码质量

    如何为变量起名 在计算机科学领域,有一句著名的格言(俏皮话): There are only two hard things in Computer Science: cache invalidati ...

  6. Spring Cloud报错Error creating bean with name 'requestMappingHandlerMapping'

    如果我们使用Spring Cloud的Feign实现熔断,首先需要自定义一个熔断类,实现你的feign接口,然后实现方法,这些方法就是熔断方法,最后需要在你的feign接口中指定fallback为自定 ...

  7. Linux(CentOS7)修改默认yum源为国内的阿里云、网易yum源

    修改方式: echo 备份当前的yum源 mv /etc/yum.repos.d /etc/yum.repos.d.backup4comex echo 新建空的yum源设置目录 mkdir /etc/ ...

  8. 小白学 Python 爬虫(11):urllib 基础使用(一)

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  9. 【JavaEE】之MyBatis开发DAO

    在SSM框架中的DAO层就是MyBatis中的Mapper,Mapper分为两部分:Mapper接口(JAVA文件)和Mapper映射文件(XML文件).DAO开发(Mapper开发)有两种方式:原始 ...

  10. centos 7 MysSQL 5.7.23 二进制安装

    MySQL 5.7.23 二进制安装 CentOS 7 将默认数据库MySQL替换成了Mariadb. 这里会从系统的环境准备开始一步一步安装. 环境准备 系统版本 内核版本 IP地址 Centos ...