Skip to content

python数据分析

利用python进行数据分析 Chap3 用序列创建字典

1
2
3
4
5
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import statsmodels as sm

环境配置

Chapter2 还有好多没学会的命令欧

ipython

ipython 是 python 的交互式 shell,使用 pip3 install ipython 安装 ipython

使用 ipython 命令打开 ipython shell,exit() 退出

Jupyter

Jupyter Notebook 可以直接在网页中编写代码和运行代码

启动 Jupyter:

jupyter notebook

生成 .ipynb 文件

⇧↩︎执行一行代码

在变量前后使用 ? 可以显示对象的信息

print?
Signature: print(*args, sep=' ', end='\n', file=None, flush=False)
Docstring:
Prints the values to a stream, or to sys.stdout by default.

sep
  string inserted between values, default a space.
end
  string appended after the last value, default a newline.
file
  a file-like object (stream); defaults to the current sys.stdout.
flush
  whether to forcibly flush the stream.
Type:      builtin_function_or_method

对象是函数:

截屏2024-12-31 16.57.50

Python基础

元组, 列表, 字典

元组

  • ()

  • tuple 将序列转换为元组

  • 创建后不可改变,但如果元组的元素是 listdict,可以在原位修改

  • + 拼接 * 复制

  • 拆分:

In [23]: tup = 4, 5, (6, 7)
In [24]: a, b, (c, d) = tup
  • *rest 可以抓取任意长度列表
1
2
3
4
In [31]: values = 1, 2, 3, 4, 5
In [32]: a, b, *_ = values
In [33]: a, b
Out[33]: (1, 2)
  • count() 统计某个值的出现频率

列表

  • [] list()

  • append 追加,extend([elem1, elem2]) 追加多个元素 (比 + 快)

  • insert(pos, element) 插入元素,插入的序号在 0 和列表长度之间

  • pop(pos) 移除并返回指定位置的元素

  • remove(element) 寻找第一个值并除去

  • bisect 模块支持二分查找

1
2
3
4
5
6
7
In [71]: import bisect
In [72]: c = [1, 2, 2, 2, 3, 4, 7]    # 有序 (升序)
In [73]: bisect.bisect(c, 2)  # 找到插入位置
Out[73]: 4
In [75]: bisect.insort(c, 6)  # 插入元素
In [76]: c
Out[76]: [1, 2, 2, 2, 3, 4, 6, 7]
  • seq[start: end: step] 左闭右开

  • enumerate() 返回 (i, value) 元组序列

  • zip(seq1, seq2) 成元组列表 [( , ), ( , )]

字典

  • {}
  • del d1[key] 删除,ret = d1.pop('key') 删除并返回值
  • update() 融合另一个字典