1. ❀【PYTHON基本语法学习】
计数遵循从零开始,左闭右开的原则
1.1 【常见的数据类型】
1. 整型-int-即整数值
int_ = 1
print('类型为:%s'%type(int_))
#输出
类型为:<class 'int'>
2. 浮点型-float-带小数点的数字
float_ = 1.0
print('类型为:%s'%type(float_))
#输出
类型为:<class 'float'>
3. 字符串型-string
以单引号或双引号括起来的任意文本,比如'hello'和"hello",字符串还有原始字符串表示法、字节字符串表示法、Unicode字符串表示法,而且可以书写成多行的形式(用三个单引号或三个双引号开头,三个单引号或三个双引号结尾)
string_ = '关于我在B站学习数据分析这档事儿 '
print('类型为:%s'%type(string_))
print(string_)
#输出
类型为:<class 'str'>
关于我在B站学习数据分析这档事儿
4. 布尔型-bool
布尔值只有True、False两种值,要么是True,要么是False,在Python中,可以直接用True、False表示布尔值(请注意大小写),也可以通过逻辑运算得到(><=)。布尔值一般用在程序流程的控制中,程序可以根据这个布尔判断进行下一步的工作。
bool_ = True
print('类型为:%s'%type(bool_))
#输出
类型为:<class 'bool'>
互相转换:
- int():将一个数值或字符串转换成整数,可以指定进制。
- float():将一个字符串转换成浮点数。
- str():将指定的对象转换成字符串形式,可以指定编码。
- chr():将整数转换成该编码对应的字符串(一个字符)。
- ord():将字符串(一个字符)转换成对应的编码(整数)。
- 也就是,我把我套到你身上,你就会变成我的类型。
print(float_) print(int(float_)) print(str(float_)) #输出 1.0 1 <class 'str'>
1.2 【条件分支】+break
###原型
if 条件1: #条件后要加冒号,结果必须换行与缩进
结果1
elif 条件2:
结果2
else:
结果3
###举例
#用法不用掌握,理解什么是条件判断就好
a = 10 #定义a,b,c三个变量,ab是运算对象,c是运算结果
b = 5
c = 0
x = input('你想做加法还是减法还是乘法还是除法?:') #x是我们输入的运算符
#根据我们输入的运算符来选择相应的运算公式
if x == '+':
c = a+b
print('{}{}{}={}'.format(a,x,b,c))
elif x == '-':
c = a-b
print('{}{}{}={}'.format(a,x,b,c))
elif x == '*':
c = a*b
print('{}{}{}={}'.format(a,x,b,c))
elif x == '/':
c = a/b
print('{}{}{}={}'.format(a,x,b,c))
else:
print('要输入加减乘除的符号哦,请重新运行输入')
#输出:
你想做加法还是减法还是乘法还是除法?:*
10*5=50
1.3 【循环结构】
1、序列:
- 列:这里的列指的不是一列,而是一个空间,这个空间里面有多个值。例如我们的列表: [1,2,3] 这个方括号就是一个空间,里面可以放入123多个值
- 序:有顺序的意思,列中的每个值,都有自己的序号,从0开始。
2、len函数:
len是lenghth的意思,长度。每个序列都有自己的长度,即有多少个值,就有多长。
例如[1,2,3]的长度就为3,写作:len([1,2,3])
3、range函数:
··range的中文意思是范围,一个范围是需要起点和终点的
··range函数的原型是 range(start,end,scan)。里面三个参数分别是起点,终点,步长
··range函数返回的是一个序列
list_ = [3,2,1] #列表,是序列的一种
list_
#输出
[3, 2, 1]
-------------------------------------
len(list_)
#输出
3
-------------------------------------
range(101)
#输出
range(0, 101) #左闭右开 从0到100的101个连续数字的序列
【for-in循环】
###原型
for 变量 in 序列
---------------------------------------------------------------------------
###举例
count = 1
for i in [3,6,4,32,3]:
print('\n现在执行第{}次循环,输出的值是:{}'.format(count,i))
count = count+1
#输出
现在执行第1次循环,输出的值是:3
现在执行第2次循环,输出的值是:6
现在执行第3次循环,输出的值是:4
现在执行第4次循环,输出的值是:32
现在执行第5次循环,输出的值是:3
---------------------------------------------------------------------------
###举例
sum = 0
for x in range(5):
sum = x + sum
print('\n现在执行第{}次循环,sum目前的值是:{}'.format(x+1,sum))
print('\n最终的值为:%d'%sum)
#输出
现在执行第1次循环,sum目前的值是:0
现在执行第2次循环,sum目前的值是:1
现在执行第3次循环,sum目前的值是:3
现在执行第4次循环,sum目前的值是:6
现在执行第5次循环,sum目前的值是:10
最终的值为:10
【while循环】
###原型 若不明确循环次数,需要满足某个条件才结束循环
while(表达式):
###举例
tempreture = 0 #设置变量 并赋值为0
while (tempreture < 106):#若温度<106度,则继续执行循环
print('你的体温正在上升:{}'.format(tempreture))
tempreture = tempreture + 15 #每一次循环,变量都增加15
print("\n我热爱{}°C的你🧐".format(tempreture-15))
#输出:
你的体温正在上升:0
你的体温正在上升:15
你的体温正在上升:30
你的体温正在上升:45
你的体温正在上升:60
你的体温正在上升:75
你的体温正在上升:90
你的体温正在上升:105
我热爱105°C的你🧐
1.4 【模块调用】
from 模块 import 功能
like:
from math import sin
即可使用sin函数功能
1.5 【自定义函数】
###原型
def 名字(参数1,参数2,参数3...):
(缩进)表达式
(缩进)return 返回的变量
-----------------------------------------------------------
###举例
def pay(x):
y = 5*x + 5
return print('🍉这瓜保熟,%d斤%d块钱' % (x,y))
weight = int(input('你要买几斤西瓜?\n'))
pay(weight)
#输出
你要买几斤西瓜?
5
🍉这瓜保熟,5斤30块钱
【匿名函数】
###定义结构
函数原型: lambda 变量1,变量2...变量n: 表达式
-------------------------------------------------------
###举例1
y = lambda x: 5*x + 5
y(2)
#输出:15
###举例2
z = lambda x,y: 5*x + y
z(2,5)
#输出:15
1.6 【数据结构】
- 字符串
1.字符串的生成 string = '我是字符串' 2.字符串连接 a = '关于我在B站' b = '学习数据分析这档事儿' a + b #输出 '关于我在B站学习数据分析这档事儿' 3.去除字符串空格 c = '关于我在B站学习数据分析这档事儿 ' d = 'I am studying Data Analyse in Bilibili' print(c.strip()) print(d.replace(' ','')) #输出 关于我在B站学习数据分析这档事儿 IamstudyingDataAnalyseinBilibili
- 列表
它是值的有序序列,多个值存储在[]方括号当中。每个值都有自己的序号(索引)
1. 列表的生成
L1 = ['凌波丽','碇真嗣','明日香']
list(enumerate(L1)) #enumerate 枚举函数 # 每个值都有自己的序号(索引)
#输出
[(0, '凌波丽'), (1, '碇真嗣'), (2, '明日香')]
#通过索引,可以取出对应的值 注意遵循从零开始
L1[1]
#输出
'碇真嗣'
----------------------------------------------------------------------------------------
2. 遍历列表
#直接遍历列表
count = 1
for i in L1: #对于每个在L1里面的i
print('现在正在遍历第{}个值,它是:{}\n'.format(count,i))
count = count + 1
#利用索引遍历列表
for i in range(len(L1)): #我们将索引代入到L1[]中
print('现在在使用索引:{},对L1进行取值,L[{}]为:{}'.format(i,i,L1[i]))
----------------------------------------------------------------------------------------
3. 列表取值
L1[0:1] #前闭后开
#输出
['凌波丽']
----------------------------------------------------------------------------------------
4. 利用append函数增添元素
###举例一
charactor = [] #这里,我们新建一个名叫 charactor的空列表
charactor.append('凌波丽')#添加一个值,叫做凌波丽
charactor
#输出
['凌波丽']
###举例二
driver = ['碇真嗣','明日香','铃原东治','真希波','渚薰'] #创建一个驾驶员的名单
count = 0
for i in driver: #对于每一个在driver里的值
count = count + 1
charactor.append(i) #每一次循环添加一个到charactor里面
print('\n执行第:{}次,charactor = {}'.format(count,charactor))
charactor
#输出
执行第:1次,charactor = ['凌波丽', '碇真嗣']
执行第:2次,charactor = ['凌波丽', '碇真嗣', '明日香']
执行第:3次,charactor = ['凌波丽', '碇真嗣', '明日香', '铃原东治']
执行第:4次,charactor = ['凌波丽', '碇真嗣', '明日香', '铃原东治', '真希波']
执行第:5次,charactor = ['凌波丽', '碇真嗣', '明日香', '铃原东治', '真希波', '渚薰']
['凌波丽', '碇真嗣', '明日香', '铃原东治', '真希波', '渚薰']
- 元组 理解为不可以增删改的列表即可
T1 = ('凌波丽','碇真嗣','明日香') T1 #输出 ('凌波丽', '碇真嗣', '明日香')
- 集合
set1 = {1, 2, 3, 3, 3, 2} set2 = {1,1,4,4,3,2} #集合内不存在重复的元素 print(set1,set2) print('Length1 = {},Length2 = {}'.format(len(set1),len(set2))) #输出 {1, 2, 3} {1, 2, 3, 4} Length1 = 3,Length2 = 4 print(set1 & set2) #交集 print(set1 | set2) #并集 print(set1 - set2) #差集 print(set1 ^ set2) #对称差集
- 字典
由键(key)和值(value)构成,形式为 key:value
一个key可以对应一个值或者是一个数据结构
1. 字典的生成
EVA1 = {'凌波丽': 'EVA零号机', '碇真嗣': 'EVA初号机', '明日香': 'EVA二号机'}
#生成方式2,用zip函数匹配列表,再使用dict()对其进行类型转换
EVA2 = dict(zip(['凌波丽','碇真嗣','明日香'], ['EVA零号机','EVA初号机',['EVA二号机','EVA三号机']]))
EVA1
EVA2
#输出
{'凌波丽': 'EVA零号机', '碇真嗣': 'EVA初号机', '明日香': 'EVA二号机'}
{'凌波丽': 'EVA零号机', '碇真嗣': 'EVA初号机', '明日香': ['EVA二号机', 'EVA三号机']}
-------------------------------------------------------------------------------------------
2. 字典的部分属性
可以使用 dict.keys() 和 dict.values() 去查看我们的键与值
print(EVA1.keys())
print(EVA2.values())
#输出
dict_keys(['凌波丽', '碇真嗣', '明日香'])
dict_values(['EVA零号机', 'EVA初号机', ['EVA二号机', 'EVA三号机']])
-------------------------------------------------------------------------------------------
3. 取值
可以根据 键 去访问 值
EVA1['明日香']
#输出
'EVA二号机'
2. 🎲【numpy】
Numerical Python:数字化python。一个科学运算与人工智能领域最常见的模块numpy
数据类型:ndarray:N维数组对象。将其理解为一个数据类型即可
ar1 = np.array([1,2,3])
type(ar1)
#输出
numpy.ndarray
ndarray生成:
np.arange(1,10)
#输出
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
-----------------------------------------------------------------------------------------
list转ndarray:
np.array(range(1,10))
#输出
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
-----------------------------------------------------------------------------------------
元素类型&转换:
#eg.1
np.array(range(1,4)).dtype
#输出
dtype('int32')
#eg.2
np.array(range(1,4)).astype('float') #将元素的类型转换为浮点型
#输出
array([1., 2., 3.])
-----------------------------------------------------------------------------------------
形状:
ar = np.array(range(0,12))
new_ar = ar.reshape(3,4) #将数组重塑为3行4列
new_ar
#输出
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
-----------------------------------------------------------------------------------------
数组运算:
arr = np.arange(0,12).reshape(3,4)
arrr = arr + arr #与自身相加
arr2 = np.arange(0,3).reshape(3,1) #arr2形状为 (3,1)
arr2 + arr #arr形状为(3,4)
arr3 = np.arange(0,4).reshape(1,4) #arr2形状为 (1,4)
arr3 + arr #arr形状为(3,4)
arr == arr4 #逻辑运算
arr
arrr
arr2
arr3
#输出:
array([[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
array([[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]])
array([[ 0, 1, 2, 3],
[ 5, 6, 7, 8],
[10, 11, 12, 13]])
array([[ 0, 2, 4, 6],
[ 4, 6, 8, 10],
[ 8, 10, 12, 14]])
2.1 【二维数组索引与切片】
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr2d[2])
print(arr2d[2][2])
#输出
[7 8 9]
9
print(arr2d[:2])
print('\n')
print(arr2d[:2][1:])#基于第一次的结果取
print('\n')
print(arr2d[:2, 1:])#在第一次结果的内部取
#输出
[[1 2 3]
[4 5 6]]
[[4 5 6]]
[[2 3]
[5 6]]
arr = np.empty((4, 4)) #创建一个4X4的空列表
for i in range(4):
arr[i] = (i+1)**2 #分别给每行赋一样的值
arr
arr[[2, 3, 0]] #选取索引 2 3 0对应的行
arr[[2, 3, 0]][[0, 2, 1]] #选取索引 0 2 3对应的行,再选取索引0 2 1对应的行
#输出
array([[ 1., 1., 1., 1.],
[ 4., 4., 4., 4.],
[ 9., 9., 9., 9.],
[16., 16., 16., 16.]])
array([[ 1., 1., 1., 1.],
[ 9., 9., 9., 9.],
[16., 16., 16., 16.]])
array([[ 9., 9., 9., 9.],
[ 1., 1., 1., 1.],
[16., 16., 16., 16.]])
注明:(不同于arr[[2,3,0]]), arr[2, 3, 0]
的含义是:首先在第一个维度上选取索引为 2
的元素,然后在该元素的基础上,在第二个维度选取索引为 3
的元素,最后在该元素的基础上,在第三个维度选取索引为 0
的元素。
2.2 【条件逻辑 三元表达式where】
xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
result = np.where(xarr>1.3, xarr, yarr)
result
#输出
array([2.1, 2.2, 2.3, 1.4, 1.5])
2.3 【基础统计方法】
arr = np.arange(0,12).reshape(3,4)#生成一个3X4的二维数组
arr
#输出
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
###求和
arr.sum()
###求平均
arr.mean()
arr.mean(axis = 0) #对列
arr.mean(axis = 1) #对行
#输出
66
5.5
array([4., 5., 6., 7.])
array([1.5, 5.5, 9.5])
2.4 【排序】
arr = np.random.randn(6) #随机生成一个一维数组
arr
#输出
array([0.26935142, 2.50972404, 0.51630414, 0.76954433, 0.32614337,
0.10278217])
-------------------------------------------------------------------------------------------
arr.sort()
arr
#输出
array([0.10278217, 0.26935142, 0.32614337, 0.51630414, 0.76954433,
2.50972404])
3. 🐼🌿【pandas】
数据类型--Series
pandas中有两种数据类型,分别为Series和DataFrame
3.1 【Series】
Series
是 pandas
中最基本的数据结构之一,它是一种类似于一维数组的对象,由一组数据(可以是不同的数据类型,如整数、浮点数、字符串等)和与之相关联的索引组成。
索引可以是默认的从 0 开始的整数索引,也可以是自定义的标签索引。
- 创建Series的方式:
1. 从列表创建:
import pandas as pd
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
在这个例子中,我们使用一个列表 [1, 3, 5, np.nan, 6, 8]
创建了一个 Series
,np.nan
表示缺失值。
2. 从字典创建:
data = {'a': 0., 'b': 1., 'c': 2.}
s = pd.Series(data)
print(s)
3. 使用标量值创建:
s = pd.Series(5., index=['a', 'b', 'c', 'd', 'e'])
print(s)
这种情况下,使用标量值 5.
创建 Series
,并为其提供自定义的索引 ['a', 'b', 'c', 'd', 'e']
,此时 Series
中的每个元素都是 5.
。
- 可以使用
index
属性访问Series
的索引,使用values
属性访问Series
的数据。
s = pd.Series([1, 3, 5, 7], index=['a', 'b', 'c', 'd'])
print(s.index)
print(s.values)
- 支持向量化操作,类似于
numpy
数组。例如,可以直接对Series
进行数学运算。
s = pd.Series([1, 3, 5, 7])
print(s + 1)
这将对 Series
中的每个元素加 1。
- 可以使用
head()
和tail()
方法查看Series
的前几个或后几个元素。
s = pd.Series(range(100))
print(s.head(5))
print(s.tail(3))
head(5)
会显示前 5 个元素,tail(3)
会显示后 3 个元素。
3.2【DataFrame】
DataFrame
是 pandas
中另一个核心的数据结构,它是一个二维的表格型数据结构,类似于电子表格或 SQL 中的表。它可以包含不同类型的数据列,并且有行和列的索引。可以将 DataFrame
看作是由多个 Series
组成的容器,其中每个 Series
代表一列数据。
- 创建
DataFrame
的方式:
1. 从字典创建:
import numpy as np
import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
print(df)
这里使用一个字典创建 DataFrame
,字典的键是列名,列表中的元素是列数据。
2. 从列表的列表创建:
data = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
print(df)
首先定义一个列表的列表,每个子列表代表一行数据,然后使用 columns
参数指定列名。
3. 从numpy数组创建:
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(arr, columns=['A', 'B', 'C'])
print(df)
先创建一个 numpy
数组,然后将其转换为 DataFrame
并指定列名。
4. 从Series创建:
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index=['a', 'b', 'c'])
df = pd.DataFrame({'col1': s1, 'col2': s2})
print(df)
这里使用两个 Series
创建 DataFrame
,Series
的名称成为 DataFrame
的列名,它们的索引会对齐。
- 访问DataFrame(df)的常见语法:
- 可以使用
columns
属性访问DataFrame
的列名,使用index
属性访问行索引。
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df.columns)
print(df.index)
#输出
Index(['A', 'B'], dtype='object')
RangeIndex(start=0, stop=3, step=1)
1. 按列访问
使用方括号 []
访问列:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# 访问 A 列
column_A = df['A']
print(column_A)
使用点运算符 .
访问列(仅当列名是有效的 Python 标识符时):
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# 访问 A 列
column_A = df.A
print(column_A)
2. 按行访问
使用 loc[]
按行标签访问:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, index=['row1', 'row2', 'row3'])
# 访问 row2 行
row_2 = df.loc['row2']
print(row_2)
使用 iloc[]
按行位置访问:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# 访问第二行(位置为 1)
row_2 = df.iloc[1]
print(row_2)
3. 同时访问行和列:
使用 loc[]
同时访问行和列(基于标签):
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, index=['row1', 'row2', 'row3'])
# 访问 row2 行和 A 列
value = df.loc['row2', 'A'] #访问第二行和第一列交叉处的元素
print(value)
使用 iloc[]
同时访问行和列(基于位置):
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# 访问第二行(位置为 1)和第一列(位置为 0)
value = df.iloc[1, 0] #访问第二行和第一列交叉处的元素
print(value)
4. 切片操作
使用 loc[]
进行切片(基于标签):
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, index=['row1', 'row2', 'row3'])
# 访问从 row1 到 row2 行和 A 列到 B 列
slice_df = df.loc['row1':'row2', 'A':'B']
print(slice_df)
#df.loc['row1':'row2', 'A':'B'] 会返回一个新的 DataFrame,包含 row1 到 row2 行和 A 列到 B 列的数据。注意,切片包含结束标签。
使用 iloc[]
进行切片(基于位置):
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# 访问前两行和前两列
slice_df = df.iloc[0:2, 0:2]
print(slice_df)
#df.iloc[0:2, 0:2] 会返回一个新的 DataFrame,包含前两行和前两列的数据。注意,切片不包含结束位置
5. 条件访问
使用布尔索引进行条件筛选:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
# 筛选出 A 列中大于 1 的行
filtered_df = df[df['A'] > 1]
print(filtered_df)
df['A'] > 1
会生成一个布尔型的 Series
,其中 True
表示满足条件的行,False
表示不满足条件的行。将这个布尔型 Series
作为 df[]
的索引,会返回一个新的 DataFrame
,其中只包含满足条件的行。
3.3【pandas与DataFrame共同对标SQL】
【SELECT & FROM】
pandas | 注释(方法的参数包括但不限于以下,更多参数可自行在 jupyter notebook 按 shift+tab 查看👀) | sql |
---|---|---|
df.column、df['column'] | 涉及选取多列,需要采用嵌套列表形式 [['x','y']] | column |
df = pd.read_csv('./table_name.csv') df = pd.read_excel('./table_name.xlsx') | read_csv() 指明所需读取表格所在的文件路径。 若表格与代码文件在同一文件夹,仅需 './ 表格名称.csv'。 若不在同一文件夹,需要右键表格属性,查看表格路径,在文件路径前加 r,如 r'C:\Users\dsx\cpc.csv'。 分隔符,常见为逗号,如 sep=',' 返回指定的列,如 usecols=[' 曝光数 ',' 进店数 '] 指定编码格式,如 encoding = 'gbk' 指定要读取的 sheet,如sheet_name='sheet2' 指定某列为索引,如 index_col=' 日期' 返回指定的列,如 usecols=[' 曝光数 ',' 进店数 '] | from |
pd.unique(df.column) pd.drop_duplicates() | unique (): 对于单个字段去重,如 unique (cpc. 日期) 对于多个字段去重,如 drop_duplicates ([' 曝光数 ',' 进店数 '])。 若对于整个 DataFrame 去重,如 cpc.drop_duplicates () | distinct |
样例1:
import numpy as np
import pandas as pd
import pymysql
pd.set_option('display.max_rows', 9999)
pd.set_option('display.max_columns', 9999)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
# - 1【select】筛选门店名称并且去重
# select distinct(平台门店名称)
# from ddm.cpc
cpc = pd.read_csv('./cpc.csv',sep = ',',encoding = 'gbk')
#确保代码文件和表格文件在同一路径下
pd.Series(pd.unique(cpc['平台门店名称']))
样例2
# - 2【select】筛选出平台门店名称,以及计算下单率
# select 平台门店名称,(门店下单量/门店访问量) as 下单率
# from ddm.cpc
cpc['符号'] = '%'
cpc['下单率'] = (round(cpc.门店下单量/cpc.门店访问量,1)*100).map(str).str.cat( cpc['符号'])
cpc['下单率']
cpc[['平台门店名称','下单率']]
#[['x1','x2']]:select
#cpc:from
【WHERE 条件筛选】
运算符 | pandas | 注释 | sql |
---|---|---|---|
> | df.query('column>x') | 通过字符串表达式对列进行筛选 | where column > x |
= | df.query('column=x') | where column = x | |
< | df.query('column<x') | where column < x | |
between..and.. | df[df.column.between(x,y)] | 参数: right/left:左右边界的值,如 between (x,y) inclusive:确定是否包括边界值,若包括 inclusive = True;若不包括,inclusive = False。默认为 True | where column between x and y |
in | df[df.column.isin([x,y,z...])] | 判断指定字段中的值是否包含在所传入的列表当中,并返回一个全为 Bool 值的 Series | where column in (x,y,z...) |
not in | df[~df.column.isin([x,y,z...])] | isnotin() | where column not in (x,y,z...) |
is null | df[df.column.isnull()] | 检测指定字段的缺失值,若出现 Nan,则映射到 True 值,非空则映射到 False。并返回与字段形状相同的 Bool 值的 Series | where column is null |
is not null | df[~df.column.isnull()] | notna() | where column is not null |
and | df.query('x<column&column<y') | python 中使用 & 表示 与 | where x<column and column <y |
or | df.query('x<column|column<y') | python 中使用 | 表示 或 | where x<column or column <y |
not | 在 df 前加一个~ | python 中使用~表示 非 | 放在配合使用的运算符前 |
query只能进行><=的筛选,其他筛选需要使用布尔索引完成(上面有嵌套的就是使用布尔索引的)
模糊查询 | pandas | 注释 | sql |
---|---|---|---|
like | df[df.column.str.contains('xxx')] | 判断所传入的字符串是否包含在我们指定字段的内容中,并返回与字段形状相同的 Bool 值的 Series 。参数: pat :字符串,如左侧实例;case :是否区分 pat 中的大小写,若区分,则 case = True ;若不区分,则 case = False 。默认为 True ,区分。 | where column like '%xxx%' |
starts with | df[df.column.str.startswith('x')] | 判断指定字段的内容是否以传入的字符串为开头,并返回与字段形状相同的 Bool 值的 Series 。参数: pat :字符串,如左侧实例。 | where column like 'x%' |
ends with | df[df.column.str.endswith('x')] | 判断指定字段的内容是否以传入的字符串为结尾,并返回与字段形状相同的 Bool 值的 Series 。参数: pat :字符串,如左侧实例。 | where column like '%x' |
样例:
#样例演示
# - 1【运算符】and:查找gmvroi>7 且 gmvroi<8 的门店ID跟名字
# select 门店ID,平台门店名称
# from ddm.cpc
# where gmvroi <=8.0
# and gmvroi >=7.0
# - 2【运算符】between and:查找门店gmvroi介于[7,8]的门店ID跟名字
# select 门店ID,平台门店名称
# from ddm.cpc
# where gmvroi between 7.0 and 8.0
cpc.query('gmvroi>=7.0&gmvroi<=8.0')[['门店ID','平台门店名称']]
#query:where
#&:and
# - 3【运算符】in:查找门店gmvroi等于[7,8]的门店ID跟名字
# select 门店ID,平台门店名称
# from ddm.cpc
# where gmvroi in(7.0,8.0)
cpc[cpc.gmvroi.isin([7.0,8.0])][['门店ID','平台门店名称']]
#cpc[['门店ID','平台门店名称']]:select 门店ID,平台门店名称
#[]内cpc:from
#gmvroi.isin():where gmvroi in()
# - 4【运算符】null:查找门店实收为空的门店ID跟名字
# select 门店ID,平台门店名称
# from ddm.cpc
# where 门店实收 is null
cpc[cpc.门店实收.isnull()][['门店ID','平台门店名称']]
#cpc[['门店ID','平台门店名称']]:select 门店ID,平台门店名称
#[]内cpc:from
#门店实收.isnull():where 门店实收 is null
# - 5【模糊查询】like:查找名称带有宝山的门店
# select distinct(平台门店名称)
# from ddm.cpc
# where 平台门店名称 like '%宝山%'
pd.Series(cpc[cpc.平台门店名称.str.contains('宝山')]['平台门店名称'].unique())
#cpc['平台门店名称']:select 平台门店名称
#[]内cpc:from
#平台门店名称.str.contains('宝山'):平台门店名称 like '%宝山%'
#unique():distinct
#pd.Series:将结果转换为Series类型
【聚合函数 & GROUP BY &HAVING】
聚合函数 | pandas | sql |
---|---|---|
AVG() | df.column.mean() | select avg(column) from df |
COUNT() | df.column.count() | select count(column) from df |
MAX() | df.column.max() | select max(column) from df |
MIN() | df.column.min() | select min(column) from df |
SUM() | df.column.sum() | select sum(column) from df |
分组筛选 | pandas | 注释 | sql |
---|---|---|---|
group | df.groupby ('column').agg (列名 = ('values','sum')) df.groupby (['column1', 'column2']).agg (列名 = ('values','sum')) | groupby('column'): 指定我们的分组字段 聚合函数 我们对聚合字段名别名 数值型字段的名字 聚合函数的名字,也可以是 max、min 等 | group by column |
having | df.groupby ('column').agg (列名 = ('values','sum')).query (' 列名 > x') | 通过对分组聚合后形成的表格,进行 query 条件筛选 | having sum(value)>x |
# - 1【聚合函数】avg:查找各个门店的平均实收
# select 平台门店名称,avg(门店实收) as 平均实收
# from ddm.cpc
# group by 平台门店名称
cpc.groupby('平台门店名称').agg(平均实收 = ('门店实收','mean'))
#cpc:from
#groupby('平台门店名称'):group by 平台门店名称
#agg(平均实收 = ('门店实收','mean')):avg(门店实收) as 平均实收
#最终结果会显示所有提到的字段
# - 2【分组筛选】having:查找实收>10k的门店名称 与 实收,按实收降序
# select 平台门店名称,sum(门店实收)
# from ddm.cpc
# group by 平台门店名称
# having sum(门店实收)>10000
# order by sum(门店实收) desc
cpc.groupby('平台门店名称').agg(总合 = ('门店实收','sum')).query('总合>10000').sort_values(by = '总合',ascending=False)
#cpc:from
#groupby('平台门店名称'):group by 平台门店名称
#agg(总合 = ('门店实收','sum')):sum(门店实收)
#query('总合>10000'):having sum(门店实收)>10000
#sort_values(by = '总合',ascending=False):order by sum(门店实收) desc
【ORDER BY】
排序 | pandas | 注释 | sql |
---|---|---|---|
正序 | df.sort_values(by = 'column', ascending = True) | 参数: 选择排序依据的字段。若需要依据多列,则使用 ['x1', 'x2']。 选择排序方式。 若正序,则 ascending = True; 若倒序,则 ascending = False | order by column asc |
倒序 | df.sort_values(by = 'column', ascending = False) | - | order by column desc |
上面那个样例有
【LIMIT】
限制 | pandas | 注释 | sql |
---|---|---|---|
limit x | df.head(x) | 取前 x 行 | limit x |
limit x,y | df [x:y] /df.loc [x:y,' 字段 '] | 跳过前 x 行,取 y 行 | limit x,y |
limit x offsets y | df[x:y] | 跳过前 x 行,取 y 行 | limit x offsets y |
# - 习题1【LIMIT】limit x,y:跳过前5行,显示5条数据
# select *
# from ddm.cpc
# limit 5,5
cpc[5:10]
在 Python 中,当使用方括号[]
进行切片操作时,对于像列表、数组以及pandas
的DataFrame
和Series
等数据结构,切片操作默认是作用于第一个维度的。 注意是从0开始的左闭右开,所以返回的是第6、7、8、9、10个商家的数据。
# 习题2【LIMIT】查找前5行的门店名称
# select 平台门店名称
# from ddm.cpc
# limit 5
cpc.loc[:5,'平台门店名称']
#输出:
0 蛙小辣火锅杯(合生汇店)
1 蛙小辣美蛙火锅杯(大宁国际店)
2 蛙小辣·美蛙火锅杯(长风大悦城店)
3 蛙小辣·美蛙火锅杯(虹口足球场店)
4 利芳·一人食大盘鸡(国定路店)
5 蛙小辣·美蛙火锅杯(虹口足球场店)
Name: 平台门店名称, dtype: object
# - 习题2【LIMIT】查找门店平均实收>1K的门店名称与平均实收,显示前5条数据,结构按照平均实收降序
# select 平台门店名称,avg(门店实收) as 平均实收
# from ddm.cpc
# group by 平台门店名称
# having 平均实收 > 1000
# order by 平均实收 desc
# limit 5
cpc.groupby('平台门店名称').agg(平均实收 = ('门店实收','mean')).query('平均实收>1000').sort_values(by = '平均实收',ascending=False).head(5)
#cpc:from ddm.cpc
#groupby('平台门店名称'):group by 平台门店名称
#order by 平均实收 desc:query('平均实收>1000')
#sort_values(by = '平均实收',ascending=False):order by 平均实收 desc
#head(5):limit 5
#agg(平均实收 = ('门店实收','mean')):avg(门店实收) as 平均实收
【子查询】
```python
#先做出子查询的筛选条件
a = df1.query("value1==x")['value1']
#再将我们的条件放入isin()方法中
b = df2['column'][df2['value2'].isin(a)]
```
```sql
select column from df2
where value2 in (select value1 from df1
where value1 = x)
```
# - 1:查找实收(cpc.csv)>1K的门店名称
# select distinct 平台门店名称
# from ddm.cpc
# where 门店ID
# in
# (
# select 门店ID
# from ddm.cpc
# where 门店实收>1000
# )
a = cpc.query('门店实收>1000').门店ID #子查询条件a:门店实收>1k的门店ID
b = cpc[cpc['门店ID'].isin(a)]['平台门店名称'].unique() #将条件放入isin()当中
pd.Series(b)
【表连接】
Pandas | 注释 | sql |
---|---|---|
merge | merge :对标我们的 sql 的 join 语句 left,right :首先传入我们需要进行连接的两表名称 left/right on:其次选择左右两表的连接字段 how:最后选择连接方式 | join |
```python
df3=pd.merge(df1,df2,left_on='column1',right_on='column2',how = 'left')
```
```sql
select * from df
left join df2
on df1.column1 = df2.column2
```
```python
df3=pd.merge(df1,df2,left_on['df1_column1,df1_column2'],right_on['df2_column1','df2_column2'],how = 'left')
```
shop = pd.read_csv('./shop.csv',encoding='gbk')
# - 1【内连接】:查看门店名称(shop)的实收(cpc)(连接字段:门店ID)
# select s.门店名称
# ,sum(c.门店实收)
# from ddm.cpc c
# join ddm.shop s
# on c.门店ID = s.门店ID
# group by s.门店名称
M = pd.merge(cpc,shop,left_on = '门店ID',right_on = '门店ID',how = 'inner')
M.groupby(['门店名称']).agg(门店实收 = ('门店实收','sum'))
#代码较长,分为两段
#pd.merge:join
#cpc,shop:from cpc join shop
#left_on:左表cpc连接字段
#right_on:右表shop连接字段
#how = 'inner':(inner) join
#groupby(['门店名称']):group by s.门店名称
# - 2 继续题1,采用2个连接字段:门店ID与日期
# select s.门店名称
# ,sum(c.门店实收)
# from ddm.cpc c
# join ddm.shop s
# on c.门店ID = s.门店ID
# and c.日期 = s.日期
# group by s.门店名称
M = pd.merge(cpc,shop,left_on = ['门店ID','日期'],right_on = ['门店ID','日期'],how = 'inner')
M.groupby(['门店名称']).agg(门店实收 = ('门店实收','sum'))
【窗口函数】
- 1,分组聚合
```python
df['sum_value'] = df.groupby('column')['value'].transform('sum')
#goupby:partition by
#transform:能够输出与DataFrame行数相同的聚合;
```
```sql
select column,value,
sum(value) over(partition by column) as sum_value
```
- 2,分组排名
```python
df['dense_rank'] = df.groupby('column')['value'].rank(ascending = False,method = 'dense')
#method = 'min':rank()
#method = 'dense':dense_rank()
#method = 'first':row_number()
```
```sql
select column,value,
dense_rank(value) over(partition by column order by value desc) as dense_rank
```
# - 1:每一天/不同门店的/门店实收排名,采用日期、门店实收正序输出
# select 日期
# ,平台门店名称
# ,门店实收
# ,rank() over (partition by 日期 order by 门店实收 desc) as rankk
# from ddm.cpc
# order by 日期,门店实收 desc
cpc['rank'] = cpc.groupby('日期')['门店实收'].rank(method = 'min',ascending=False)
#这里相当于rank() over (partition by 日期 order by 门店实收 desc) as rankk
cpc.sort_values(by = ['日期','门店实收'],ascending=[True,False])[['日期','平台门店名称','门店实收','rank']]
#sort_values(by = ['日期','门店实收'],ascending=[True,False]):order by 日期,门店实收 desc
#[['日期','平台门店名称','门店实收','rank']]:select 日期,平台门店名称,门店实收,rankk
cpc['rank'] = cpc.groupby(['日期','平台i'])['门店实收'].rank(method = 'min',ascending=False)
cpc
3.4【实现EXCEL的数据透视表】
table = pd.pivot_table(df, values = ['value'], index = ['column1','column2'], columns = ['column3'], aggfunc = np.num,margins=True)
#1、df:选择待处理的DataFrame,对应Excel的框选操作,若只想筛选部分字段,则df[['column1','column2','column3','values']]
#2、value:选择我们要聚合的数值字段 ,对应Excel中的值
#3、index:选择我们的索引(行标签),对应Excel的行
#4、columns:选择我们的列字段,对应Excel的列
#5、aggfunc:选择聚合函数
#6、margins:选择是否添加行&列的小计
pd.pivot_table
是 pandas
库中的一个函数,用于创建数据透视表。数据透视表是一种强大的数据分析工具,可以对数据进行汇总、聚合和重组,以更方便地查看和分析数据。
# - 1:各个门店在不同平台的商家实收
table = pd.pivot_table(cpc, values = ['门店实收','cpc总费用'], index = ['平台门店名称'], columns = ['平台i'], aggfunc = np.sum).fillna(0)
table
3.5【表格的合并】
核心思路都是采用循环,逐个拼接表格
#当想要合并不同的Excel表格(注意,要保证每个Excel表格的字段相同哦)
import numpy as np
import pandas as pd
import os
path = './test/' #1、path:选择Excel表格所在路径
files = [i for i in os.listdir(path)] #2、files = []:创建一个空列表,将路径中,文件or文件夹的名字装入列表
print(files) #3、查看是否正确,如:['test1','test2']
Merge = pd.DataFrame() #4、创建一个空的DataFrame
for i in files: #5、for:循环遍历我们的名称列表(2),
df = pd.read_excel(path+i) #6、read_excel(path+i):读取第files[i]份表格。如当i=0,files[0]='sheet1'
Merge = pd.concat([Merge,df]) #7、concat:将df内容拼接至Merge内
Merge.to_excel(path+'excel合并.xlsx',index = None) #8、to_excel:遍历结束后,输出我们合并后的表格
[i for i in os.listdir(path)]
是一个列表推导式,它的原理是基于对可迭代对象的遍历和元素提取,以下是具体说明:os.listdir(path)
:这是 Python 中os
模块的一个函数,用于返回指定路径path
下的所有文件和文件夹的名称列表。例如,如果path
指向一个包含file1.txt
、file2.csv
和folder1
的目录,那么os.listdir(path)
将返回['file1.txt', 'file2.csv', 'folder1']
。to_excel
方法的index = None
参数的作用是控制是否将DataFrame
的索引作为一列写入到 Excel 文件中,当使用to_excel
方法将DataFrame
数据写入 Excel 文件时,如果不设置index = None
,默认会将行索引作为 Excel 表格中的一列写入。
#当想要合并同一张Excel表格内的所有sheet(注意,要保证每个sheet的字段相同哦)
import numpy as np
import pandas as pd
import os
name_list = pd.ExcelFile('./test/学习名单3.xlsx') #1、ExcelFile:传入Excel表格
df_list = pd.DataFrame() #2、创建一个空DataFrame
for sheet in name_list.sheet_names: #3、for:循环遍历我们的名称列表(1)
df = name_list.parse(sheet_name=sheet) #4、name_list的属性parse:读取sheet中的内容
df_list=pd.concat([df_list,df]) #5、append:我们将读取到的sheet内容,附加到df_list中
df_list.to_excel('./test/sheet合并.xlsx',index=False) #6、将df_list中的内容按行合并,输出
#ExcelFile():传入一个表格的路径,并赋予一个对象。
#sheet_names:他是ExcelFile()的一个方法,将Excel子工作表的名字以列表形式返回
#parse:他是ExcelFile()的一个方法
#参数sheet_name:传入子工作表的名称,可以读取里面的内容
3.6【数据探索处理】
# - 0、数据准备:导入pandas库&数据
import numpy as np
import pandas as pd
#导入我们需要的包,并且给它起别名,方便我们调用
df = pd.read_csv('./cpc.csv',encoding='gbk')
#df--给我们导入的数据命名为df
#pd--调用pandas
#read_csv()--pandas常用的读取数据函数
#('文件名')--需要导入的数据文件名
# - 1、了解数据
df.info() #了解数据框架--我们数据的行列、字段的类别等概况
#rangeIndex--数据总体的行数
#data columns--数据总体的字段
#int64/object/float64...--字段数据类型,object可理解为字符串
#xxx non-null--非空的记录数
df.head(10) #了解详细数据
#可以看到我们表格内具体的数据内容
#head()--括号内不加参数,默认为5,即显示5行
df.drop(columns='updateTime',inplace = True)#当我们通过上一步:df.head()查看数据内容后,可以删除我们认为不需要的字段
#inplace--我们直接替换原有的数据
df
#- 3、数值探索
df.describe()#我们对表格内的数值型字段进行描述性统计
#count--计数
#mean--平均值
#std--标准差
#min--最小值
#25%/50%/75%--分位值
#max--最大值
4. 🎨【matplotlib】
结果在study_matplotlib.ipynb中
【pyplot绘图】
pyplot:大多数matplotlib实用程序位于pyplot子模块下,通常以plt别名导入
#在图中从位置(0,0)到位置(6,250)画一条线
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0,6])
ypoints = np.array([0,250])
plt.plot(xpoints,ypoints)
plt.show
plotting:plot()函数用于在图表中绘制点(标记
默认情况下,plot()从点到点绘制一条线,该函数采用参数来制定图中的点
参数1:一个包含x轴上的点的数组
参数2:一个包含y轴上的点的数组
如果我们需要绘制一条从(1,3)到(8,10)的线,我们必须将两个数组[1,8]和[3,10]传递给plot函数
#无线绘图 仅绘制标记,使用快捷字符串符号参数“o”,代表“环”
#在图中绘制两个点,一个在位置(1,3),一个在位置(8,10)
plt.plot(xpoints, ypoints, 'o')
plt.show
#多点:根据需要绘制任意数量的点,只需确保两个轴上的点数相同即可
#在途中画一条线,从位置(1,3)到(2,8)到(6,1)到(8,10)
xpoints = np.array([1,2,6,8])
ypoints = np.array([3,8,1,10])
plt.plot(xpoints, ypoints)
plt.show
如果不指定x轴上的点,将获得默认值0、1、2、3... plt.plot(ypoints)
【标记】
markers 标记:使用关键字参数marker,用指定的标记强调每个点
ypoints= np.array([3,8,1,10])
plt.plot(ypoints, marker = 'o')
plt.show()
Marker | Description |
---|---|
'o' | Circle |
'*' | Star |
'.' | Point |
',' | Pixel |
'x' | X |
'X' | X (filled) |
'+' | Plus |
'P' | Plus (filled) |
's' | Square |
'D' | Diamond |
'd' | Diamond (thin) |
'p' | Pentagon |
'H' | Hexagon |
'h' | Hexagon |
'v' | Triangle Down |
'^' | Triangle Up |
'<' | Triangle Left |
'>' | Triangle Right |
'1' | Tri Down |
'2' | Tri Up |
'3' | Tri Left |
'4' | Tri Right |
'|' | Vline |
'_' | Hline |
【线条】
格式化字符串fmt:可以使用快捷字符串符号参数来指定标记,此参数也称为fmt,使用以下语法编写 marker,line,color
ypoints = np.array([3,8,1,10])
plt.plot(ypoints,'o:r')
# 'o' 表示使用圆形标记数据点
# ':' 表示使用虚线连接数据点
# 'r' 表示使用红色绘制线条和标记
plt.show()
#指定标记尺寸:使用关键字参数markersize或ms设置标记的大小
ypoints = np.array([3,8,1,10])
plt.plot(ypoints, marker = 'o',ms = 20)
plt.show()
#标记颜色
#使用关键字参数 markeredgecolor 或 mec 来设置标记边缘的颜色
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r')
plt.show()
#关键字参数 markerfacecolor 或较短的 mfc 来设置标记边缘内的颜色
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, marker = 'o', ms = 20, mfc = 'r')
plt.show()
不同指定颜色的方法:
- 使用十六进制颜色值:
- plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc = '#4CAF50')
-
plt.plot(ypoints, marker = 'o', ms = 20, mec = 'hotpink', mfc = 'hotpink')
# 线型:可以使用关键字参数linestyle或ls来更改该绘制线的样式
ypoints = np.array([3,8,1,10])
plt.plot(ypoints,linestyle = 'dotted') #/dashed
plt.show()
Line Syntax | Description |
---|---|
'-' | Solid line |
':' | Dotted line |
'--' | Dashed line |
'-.' | Dashed/dotted line |
#使用关键字参数color或c来设置线条的颜色:
ypoints = np.array([3,8,1,10])
plt.plot(ypoints,color = 'r')
plt.show()
#线宽度 使用关键字参数linewidth或lw来更改线条的宽度
ypoints = np.array([3,8,1,10])
plt.plot(ypoints, linewidth = '20.5')
plt.show()
#通过简单地添加更多plt.plot()函数来绘制任意数量的线
y1 = np.array([3,8,1,10])
y2 = np.array([6,2,7,11])
plt.plot(y1)
plt.plot(y2)
plt.show
#x和y值成对出现
x1 = np.array([0,1,2,3])
y1 = np.array([3,8,1,10])
x2 = np.array([0,1,2,3])
y2 = np.array([6,2,7,11])
plt.plot(x1,y1,x2,y2)
plt.show()
Color Syntax | Description |
---|---|
'r' | Red |
'g' | Green |
'b' | Blue |
'c' | Cyan |
'm' | Magenta |
'y' | Yellow |
'k' | Black |
'w' | White |
【标签、标题】
#labels 为绘图创建标签
#title 为绘图创建标题
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['KaiTi'] #设置 matplotlib 的字体参数,将无衬线字体设置为 “楷体”,用于在图表中正确显示中文。
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.title("运动手表数据") #使用title()函数为绘图设置标题
plt.xlabel("平均脉搏")
plt.ylabel("卡路里消耗量") #使用pyplot,使用xlabel()和ylabel()函数为x轴和y轴设置标签
plt.show()
#设置标题和标签的字体属性
#使用xlabel(),ylabel(),title()中的fontdict参数来设置标题和标签的字体属性
import matplotlib
matplotlib.rcParams['font.family'] ='sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
font1 = {'color': 'blue','size': 20}
font2 = {'color': 'darkred','size': 15}
plt.title("运动手表数据", fontdict = font1)
plt.xlabel("平均脉搏", fontdict = font2)
plt.ylabel("卡路里消耗量", fontdict = font2)
plt.plot(x, y)
plt.show()
#定位标题
#使用 title() 中的 loc 参数来定位标题,合法值是 “left”、“right” 和 “center”,默认值为 “center”
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("运动手表数据", loc = 'left')
plt.xlabel("平均脉搏")
plt.ylabel("卡路里消耗量")
plt.plot(x, y)
plt.show()
【网格线】
#向绘图中添加网格线
#使用pyplot,使用grid()函数将网格线添加至绘图中
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("运动手表数据")
plt.xlabel("平均脉搏")
plt.ylabel("卡路里消耗量")
plt.plot(x, y)
plt.grid()
# plt.grid(axis = 'x') #指定要显示的网格线,默认值为“both”
#plt.grid(color = 'green',linestyle = '--',linewidth = 1.5) #指定要显示的网格线,默认值为“both”
plt.show()
【多图】
#subplots()函数,在一张图中绘制多个图
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1) #创建一个 1 行 2 列的子图布局,并选择第 1 个子图进行操作
plt.plot(x, y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2) #创建一个 1 行 2 列的子图布局,并选择第 1 个子图进行操作
plt.plot(x, y)
plt.show()
#subplots() 函数采用三个参数来描述图形的布局。
#布局按行和列组织,由第一个和第二个参数表示。第三个参数表示当前绘图的索引。
# 如果我们想要一个 2 行 1 列的图形(这意味着两个图将垂直显示而不是并排显示),我们可以编写如下语法:
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
# 该图有 2 行 1 列,该子图是第一个图。
plt.subplot(2, 1, 1)
plt.plot(x, y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
# 该图有 2 行 1 列,该子图是第二个图。
plt.subplot(2, 1, 2)
plt.plot(x, y)
plt.show()
#使用title()函数为每个图添加标题
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1) #创建一个 1 行 2 列的子图布局,并选择第 1 个子图进行操作
plt.plot(x, y)
plt.title("sales")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2) #创建一个 1 行 2 列的子图布局,并选择第 1 个子图进行操作
plt.plot(x, y)
plt.title("income")
plt.show()
#超级标题,可以使用suptitle()函数为整个图形添加标题
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1) #创建一个 1 行 2 列的子图布局,并选择第 1 个子图进行操作
plt.plot(x, y)
plt.title("sales")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2) #创建一个 1 行 2 列的子图布局,并选择第 1 个子图进行操作
plt.plot(x, y)
plt.title("income")
plt.suptitle("my shop")
plt.show()
【散点图、柱状图、直方图、饼图】
【散点图】
# 创建散点图
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y)
plt.show()
# 设置散点图颜色:使用 color 或 c 参数为每个散点图设置自己的颜色
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
plt.scatter(x, y, color='hotpink')
x = np.array([2, 2, 8, 1, 15, 8, 12, 9, 7, 3, 11, 4, 7, 14, 12])
y = np.array([100, 105, 84, 105, 90, 99, 90, 95, 94, 100, 79, 112, 91, 80, 85])
plt.scatter(x, y, color='#88c999')
plt.show()
#给每个点上色:可以通过使用颜色数组作为 c 参数的值来为每个点设置特定颜色,不能为此使用 color 参数,只能使用 c 参数。
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
colors = np.array(["red", "green", "blue", "yellow", "pink", "black", "orange", "purple", "beige", "brown", "gray", "cyan", "magenta"])
plt.scatter(x, y, c=colors)
plt.show()
#如何使用颜色图:
#可以使用带有颜色图值的关键字参数 cmap 指定颜色图,在本例中为 viridis,它是 Matplotlib 中可用的内置颜色图之一。
# 此外创建一个包含值(从 0 到 100)的数组,散点图中的每个点都有一个值。通过 plt.colorbar() 语句在绘图中包含颜色图
x = np.array([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6])
y = np.array([99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])
plt.scatter(x, y, c=colors, cmap='viridis')
plt.colorbar() #在图形中添加颜色条,用于显示颜色图与值的对应关系,帮助理解每个点的颜色所代表的值。
plt.show()
#组合颜色、大小和透明度:在点上组合具有不同大小的颜色图
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')
#cmap从 nipy_spectral 颜色图中选取颜色为每个点上色
#s = sizes指定大小
#alpha = 0.5 调整点的透明度
plt.colorbar()
plt.show()
【柱状图】
# 创建柱状图:在 Pyplot 包中,使用 bar() 函数绘制柱状图
# bar() 函数采用描述条形布局的参数,类别及其值由第一个和第二个参数表示为数组
x = np.array(["A", "B", "C", "D"]) #也可换成其他文本
y = np.array([3, 8, 1, 10])
plt.bar(x, y)
plt.show()
#plt.bar(x, y, color="red") 使用关键字参数 color 来设置颜色
#plt.bar(x, y, width=0.1) 使用关键字参数 width 来设置条形粗度
#plt.barh(x, y, height=0.1) 使用关键字参数 height 来设置条形粗度
#水平柱状图:如果柱状水平显示而不是垂直显示,请使用 barh() 函数。
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.barh(x, y)
plt.show()
【直方图】
#创建直方图:在 Matplotlib 中,我们使用 hist() 函数来创建直方图。
# hist() 函数将使用一个数字数组来创建直方图,该数组作为参数发送到函数中。
# 为简单起见,我们使用 NumPy 随机生成一个包含 250 个值的数组,其中值将集中在 170 左右,标准差为 10
x = np.random.normal(170, 10, 250)
print(x)
plt.hist(x)
plt.show()
【饼图】
#创建饼图:在 Pyplot 包中,可以使用 pie() 函数绘制饼图。
#标签:使用 label 参数为饼图添加标签。label 参数必须是一个数组,每个楔形都有一个标签。
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels=mylabels)
plt.show()
# 默认起始角度位于x轴,但可以通过指定startangle参数来更改起始角度(逆时针)
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels=mylabels, startangle = 90)
plt.show()
#Explode:突出某一块
# 如果指定了 explode 参数,而不是 None,则必须是一个数组,每个楔形都有一个值。每个值表示每个楔形显示的距离中心多远
# 阴影:通过将 shadow 参数设置为 True 为饼图添加阴影
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
myexplode = [0.2, 0, 0, 0]
plt.pie(y, labels=mylabels, explode=myexplode, shadow=True)
plt.show()
# 颜色:使用 colors 参数设置每个楔形的颜色。如果指定了颜色参数,则必须是一个数组,每个楔形都有一个值。
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]
plt.pie(y, labels=mylabels, colors=mycolors)
plt.show()
# 图例:要为每个楔形添加解释列表,请使用 legend() 函数
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.pie(y, labels=mylabels)
plt.legend(title = 'fruits')
plt.show()
5.【十个常见基本算法模型】(施工中...)
Machine Learning: 十大机器学习算法 - 知乎
参考ISLP/ISLR
机器学习算法大致可以分为三类:
监督学习算法 (Supervised Algorithms):(样本中没有分类结果)
在监督学习训练过程中,可以由训练数据集学到或建立一个模式(函数 / learning model),并依此模式推测新的实例。
该算法要求特定的输入/输出,首先需要决定使用哪种数据作为范例。例如,文字识别应用中一个手写的字符,或一行手写文字。主要算法包括神经网络、支持向量机、最近邻居法、朴素贝叶斯法、决策树等。
无监督学习算法 (Unsupervised Algorithms):
这类算法没有特定的目标输出,算法将数据集分为不同的组。
强化学习算法 (Reinforcement Algorithms):(样本中有分类结果)
强化学习普适性强,主要基于决策进行训练,算法根据输出结果(决策)的成功或错误来训练自己,通过大量经验训练优化后的算法将能够给出较好的预测。类似有机体在环境给予的奖励或惩罚的刺激下,逐步形成对刺激的预期,产生能获得最大利益的习惯性行为。在运筹学和控制论的语境下,强化学习被称作“近似动态规划”(approximate dynamic programming,ADP)。
基本的机器学习算法:(8+2)
一、线性回归算法 Linear Regression
线性回归是一种用于建立变量之间线性关系的监督学习算法,旨在找到一条直线(对于一元线性回归 Simple Linear Regression)或一个超平面(对于多元线性回归Multiple Linear Regression)来最好地拟合数据点。
其数学模型可以表示为:
对于一元线性回归
对于多元线性回归
目标是最小化损失函数,最常用的是最小二乘法,即最小化预测值与真实值之间的平方差的总和。通过求解这个优化问题来确定模型的参数。从几何角度看,就是找到一条直线或超平面,使得所有数据点到该直线或超平面的垂直距离的平方和最小。
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
# 生成一些示例数据
np.random.seed(0)
x = np.random.rand(100, 1)
y = 2 + 3 * x + np.random.randn(100, 1)
# 创建线性回归模型
lin_reg = LinearRegression()
lin_reg.fit(x, y)
# 输出模型的参数
print("截距:", lin_reg.intercept_)
print("斜率:", lin_reg.coef_)
# 预测新数据
x_new = np.array([[0], [1]])
y_pred = lin_reg.predict(x_new)
# 可视化数据和拟合直线
plt.scatter(x, y)
plt.plot(x_new, y_pred, "r-")
plt.show()
代码解释:
- 首先使用
numpy
生成一些带有噪声的示例数据,其中y
是x
的线性函数加上一些随机噪声。 - 创建
LinearRegression
对象并使用fit
方法对数据进行拟合,这将自动计算出最佳的模型参数。 - 使用
intercept_
和coef_
属性获取模型的截距和斜率。 - 使用
predict
方法对新数据x_new
进行预测。 - 最后使用
matplotlib
绘制数据散点图和拟合直线,红色直线为拟合的线性回归模型。
二、支持向量机算法 (Support Vector Machine,SVM)
支持向量机是一种监督学习模型,主要用于分类问题。它通过找到最佳的超平面,将数据分为不同的类别,以最大化分类边界的距离。
需要注意的是,支持向量机需要对输入数据进行完全标记,仅直接适用于两类任务,应用将多类任务需要减少到几个二元问题。
对于线性可分的数据,优化问题可以表示为:
三、最近邻居/k-近邻算法 (K-Nearest Neighbors,KNN)
K近邻是一种简单的分类算法,通过计算新样本与训练样本的距离,选择距离最近的K个邻居进行分类预测。
四、逻辑回归算法 Logistic Regression
逻辑回归是一种分类算法,主要用于二分类问题。它通过逻辑函将预测值映射到0到1之间,从而实现分类。
五、决策树算法 Decision Tree
决策树是一种树状结构的分类和回归模型。它通过一系列的决策节点对数据进行分类,每个节点根据特征值将数据分为不同的子集,直至到达叶节点。
它通过对特征空间进行递归划分,将数据集分成多个子集,每个子集对应树中的一个节点。决策树的构建是一个贪心过程,从根节点开始,在每个节点处选择一个最优的特征进行划分,以使得划分后的子节点的纯度或不纯度得到最大程度的提升。
对于分类问题,常用的不纯度度量指标有信息增益(基于信息熵)、信息增益比和基尼指数。以信息增益为例,对于一个数据集D, 信息熵的定义为:
其中 是类别 k 在数据集 D 中的概率。假设根据特征 A 对数据集 D 进行划分,产生了 V 个子集
则信息增益为:
决策树在每个节点选择信息增益最大的特征作为划分特征。
六、k-平均聚类算法 K-Means Clustering
K均值聚类是一种无监督学习算法,用于将数据集分为K个簇。算法通过迭代优化,使每个簇内的数据点尽可能接近其中心点。
七、随机森林算法 Random Forest
机森林是一种集成学习方法,通过构建多个决策树来提高分类的准确性和鲁棒性。每个决策树独立地对数据进行预测,最终的分类结果通过多数投票决定。
八、朴素贝叶斯算法 Naive Bayes
朴素贝叶斯是一种基于贝叶斯定理的分类算法。它假设特征之间相互独立,通过计算每个类别的条件概率,进行分类预测。
贝叶斯定理:
对于分类任务,要预测一个样本 属于类别Y的概率,在朴素贝叶斯中假设特征之间相互独立,因此有