1、numpy模块使用
numpy介绍
- 一个开源的Python科学计算库
- 计算起来要比python简洁高效
- Numpy使用ndarray对象来处理多维数组
ndarray的优势
- 内存块风格
- list – 分离式存储,存储内容多样化
- ndarray – 一体式存储,存储类型必须一样
- ndarray支持并行化运算(向量化运算)
- ndarray底层是用C语言写的,效率更高,释放了GIL
# 基本操作类似于列表,支持sort(), max(), min()及切片[起始下标:结束下标(不包含):步长]等
import numpy
# 创建一维数组
x = numpy.array([mem1, mem2, mem3])
# 创建二维数组
y = numpy.array([[mem1, mem2, mem3...], [mem4, mem5, mem6...], [mem7, mem8, mem9...]...])
# 数组整合
numpy.concatenate((x, y))
2、pandas模块使用官方文档
pandas的优势
- 增强图表可读性
- 便捷的数据处理能力
- 读取文件方便
- 封装了Matplotlib、Numpy的画图和计算
import pandas as pd
# Series
x = pd.Series([mem1, mem2, mem3], index=['one', 'two', 'three'])
# DataFrame
y1 = pd.DataFrame([[mem1, mem2, mem3...], [mem4, mem5, mem6...], [mem7, mem8, mem9...]...], columns=[...])
y2 = pd.DataFrame({
'one':4, # one two three
'two':[6, 2, 3], # 0 4 6 7
'three':list(str(789)) # 1 4 2 8
}) # 2 4 3 9
# 取前n行数据,默认五行
y2.head()
# 取后n行数据,默认五行
y2.tail()
# 简单统计
>>>y2.describe()
'''
one two
count 3.0 3.000000 # 元素个数
mean 4.0 3.666667 # 平均值
std 0.0 2.081666 # 标准差
min 4.0 2.000000 # 最小值
25% 4.0 2.500000 # 分位数
50% 4.0 3.000000 # 分位数
75% 4.0 4.500000 # 分位数
max 4.0 6.000000 # 最大值
'''
# 转置 T
>>>y2.T
'''
0 1 2
one 4 4 4
two 6 2 3
three 7 8 9
'''
3、数据导入
import pandas as pd
import pymysql
# 读取SQL数据库数据
conn = pymysql.connect(host='', user='', passwd='', db='')
data = pd.read_sql(sql语句, coon)
# i = pd.read_html() # 读取HTML格式文件数据
# i = pd.read_table() # 读取TXT格式文件数据
# i = pd.read_csv() # 读取CSV格式文件数据
i = pd.read_excel() # 读取Excel格式文件数据
# 统计排序
result = i.describe()
result.sort_values(by='count') # 按照count排序
4、pandas方法
pandas.cut(data, 3, label=['one', 'two', 'three']) # 3等分,label指定名字
pandas.cut(data, [1, 2, 3], label=['one', 'two', 'three']) # 按照长度分别为1, 2, 3离散