一、numpy
numpy是python数据分析和机器学习的基础模块之一。它有两个作用:1.区别于list列表,提供了数组操作、数组运算、以及统计分布和简单的数学模型;2.计算速度快[甚至要由于python内置的简单运算],使得其成为pandas、sklearn等模块的依赖包。高级的框架如TensorFlow、PyTorch等,其数组操作也和numpy非常相似。
1、随机数生成
常用的生成随机数的几个函数:
li = list(range(10))
print(li, type(li))
li = np.array(li)
print(li, type(li))
li = li.tolist() # list(li)也可以
print(li, type(li))
list和array互相转化
np.random.rand(10, 5) # 生成[0, 1]之间均匀分布的数组10行,5列
np.random.randn(10, 5) # 生成[0, 1]之间均匀分布的数组10行,5列
np.random.randint(10, 20, size=(10, 5)) # 生成[10, 20]之间随机数组10行,5列
np.random.random(size=(10, 5)) # 生成[0, 1]之间的10行5列的数组
li = list(range(10))
np.random.choice(li, size=(10, 5)) # 从li中产生随机数,生成10行5列的数组
np.arange(10, 20, 2, ) # 从[10, 20]中以步长为2生成一维数组
函数使用
其它不常见的随机数生成函数:
np.random.binomial(100, 0.5, size=(10, 5))
二项分布
2、数组切片
array对象的切片和list列表的切片操作相同。记住一个规则array[start: end: step]。
dt = np.random.binomial(100, 0.5, size=(10, 5))
dt[1: 3, :]
dt[[1,5], :]
dt[[1, 4, 7]]
dt[:, [2, 4]]
数组切片
一维和n维数组的转化
li = np.random.random((1, 100)).reshape(20, 5) # 将1行100列的数组转换成20行5列的新数组
print(li)
li = li.reshape((2, -1)) # 将20行5列的数组转换成2行50列的新数组
# 将20行5列的数组转换为2行50列的数组,-1表示根据原数据和当前行[列]参数来自动生成列[行]数
print(li)
li = li.reshape(-1, 100) # 将2行50列的数组转换成1行100列的数组
print(li)
数组维度转化
3、数组运算
# 加法
np.sum(l1) # 有意思的sum
np.sum(l1, axis=0)
np.sum(l1, axis=1)
np.sum([l1, l2])
np.subtract(l1, l2) # 减法
np.multiply(l1, l2) # 乘法
np.divide(l1, l2) # 除法
np.power(l1, l2) # 幂乘
np.floor_divide(l1, l2) # 地板除
np.floor(l1) # 向下取整
np.ceil(l1) # 向上取整
np.dot(l1, l2.T) # 点积 l2.T表示转置
np.
# 以下和sum的使用方式相同
np.max(l1)
np.min(l1)
np.mean(l1)
np.median(l1)
np.std(l1)
np.var(l1)
# np.vander() # 必须是一维数组,
# li = np.arange(1, 5, step=1, dtype=int)
# np.vander(li, len(li))
View Code
numpy还有其它的一些常用函数,如np.exp(), np.abs()等,也可以通过np.loadtxt读取txt文件。
4、数组拼接
l1 = np.linspace(10, 20, num=72).reshape(12, 6)
l2 = np.random.random(size=(12, 6))
np.vstack((l1, l2)) # 按列拼接
np.hstack((l1, l2)) # 按行拼接
np.vsplit(l1, [3, 6, 9]) # 按行切割,参数3, 6, 9表示在第几行切割一下[包括这一行],生成一个list对象
np.hsplit(l1, [1, 3,]) # 按列切割
View Code
二、pandas
官方api: http://pandas.pydata.org/pandas-docs/stable/api.html#general-functions
pandas是python数据分析的核心模块。它主要提供了五大功能:
- 1.支持文件存取操作,支持数据库(sql)、html、json、pickle、csv(txt、excel)、sas、stata、hdf等。
- 2.支持增删改查、切片、高阶函数、分组聚合等单表操作,以及和dict、list的互相转换。
- 3.支持多表拼接合并操作。
- 4.支持简单的绘图操作。
- 5.支持简单的统计分析操作。
1、创建和存取pandas对象
dic = [
{
"name": "Li",
"age": 18,
"gender": "male"
},
{
"name": "Wusir",
"age": 16,
"gender": "female",
}
]
df = pd.DataFrame(
data=dic,
index=None,
columns=["name", "age", "gender"], # list(dic.keys()),
dtype=None, # dtype不可用列表去给每个column去定义
)
字典创建
lis = np.random.random(size=(13, 5))
index = pd.period_range(start="2017-01-01", end="2018-01-01", freq="M")
# index = pd.period_range(start=pd.Period('2017Q1', freq='Q'), end=pd.Period('2017Q2', freq='Q'), freq='M')
df= pd.DataFrame(lis, index=index, columns=list("ABCED")).reset_index(drop=False)
数组创建
df.to_csv("test", header=True, index=False)
pd.read_csv("test")
保存成csv
import pandas as pd
import threading
import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine(
"mysql+pymysql://root:1234@127.0.0.1:3306/test?charset=utf8",
max_overflow=5,
pool_size=10,
pool_timeout=30,
pool_recycle=-1,
)
df = pd.read_sql_table("test1", con=engine, columns=None)
读取一张table
import numpy as np
import pandas as pd
import pymysql
def conn(sql):
# 连接到mysql数据库
conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
passwd="1234",
db="test",
)
try:
data = pd.read_sql(sql, con=conn)
return data
except Exception as e:
print("SQL is not correct!", sep="\r\n\r\n")
finally:
conn.close()
sql = "select * from test1 limit 0, 10" # sql语句
data = conn(sql)
# print(data.columns.tolist()) # 查看字段
print(data) # 查看数据
读取sql语句