python
2021-01-16 22:10:01 1 举报
AI智能生成
python基础知识汇总
作者其他创作
大纲/内容
Introduction to python
Python Basic
变量命名规则
第一个字符必须是字母或下划线
其他部分可以是字母、数字或下划线
对大小写敏感
不能使用关键字命名
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
注释
单行注释以#开头
# import pandas as pd
多行注释''' '''
'''
line1
line2
line3
'''
line1
line2
line3
'''
多行注释""" """
"""
line1
line2
line3
"""
line1
line2
line3
"""
转义字符 \
\n 换行
\t 制表符
\a 提示音
\b 退格键(被覆盖)
\r 回车键
\f 换页
注: 在其前面加r可取消转义 例:r‘gui\nzi'
输出多个变量
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
#InteractiveShell.ast_node_interactivity = "last" #默认设置
InteractiveShell.ast_node_interactivity = "all"
#InteractiveShell.ast_node_interactivity = "last" #默认设置
a, b = 1, 2
a
b
a
b
判断类型
isinstance
isinstance(要判断的值,要判断的类型);返回True或False
isinstance (a,int)
判断给定的值是否属于指定的一堆数据类型中,返回True或False
isinstance (a,(str,int,list))
type
判断给予属于属于哪个数据类型
type(a)
df.dtypes
1. float
2. int
3. bool
4. datetime64[ns]
5. datetime64[ns, tz]
6. timedelta[ns]
7. category
8. object
2. int
3. bool
4. datetime64[ns]
5. datetime64[ns, tz]
6. timedelta[ns]
7. category
8. object
模块与包
第三方库
numpy
pandas
matplotlib
sklearn
scipy
导入模块
import
import module as new_name
form module import objectname
from module import *
from module import objectname as newname
os模块
os 可以直接调用操作系统系统提供的接口函数
os.getcwd() 当前路径
os.chdir('需要切换到的路径') 切换路径
os.name 操作系统类型分posix和nt
os.uname() 获取详细的系统信息
os.environ 获取环境变量返回一个字典,要获取某个环境变量的值可以调用os.environ.get('key')
os.path.abspath('.') 查看当前目录的绝对目录
os.path.join('绝对路径',‘目录名’) 在某个目录下创建一个新目录,首先把新目录的完整路径表示出来
os.mkdir('路径') 创建一个目录
os.makedirs('目录') 创建多层目录
os.rmdir('路径') 删除一个目录
os.path.split() 拆分一个路径
os.path.splitext() 直接得到文件扩展名
os.rename('原文件名','新文件名') 对文件重命名
os.remove('文件名') 删除文件
列出所有.py扩展名文件
列出当前目录下所有目录
shutil 模块
shutil.rmtree() 删除目录 空目录有内容的都可以
shutil.copyfile('oldfile','newfile') 两个参数都必须是文件
shutil,copy('oldfile','newfile') 第二个参数可以是文件也可以是目标目录
shutil.move('file','package') 移动文件
sys模块
sys.argv 命令行参数的列表,列表的第一个元素就是正在运行的文件名
sys.exit() 退出当前程序
sys.path 返回Python目录下所有.pth路径文件下的内容及系统默认设置
time模块
time,localtime()
time.asctime(time.localtime()) 返回一个可读性时间
time.time() 可以用来计算程序的运行用时
time.clock()
re正则
正则是一门独立的语言,处理字符串的强大工具
属性和方法
re.search('目标匹配','匹配源') 默认返回一个目标匹配, 注意Py3和2的区别,3里返回更详细
re.findall('','') 以一个列表方式返回所有满足条件的元素,遍历
re.match() 判断一个正则表达式是
re.compile('筛选条件') 提前进行编译,确立筛选条件
元字符
. 匹配换行符之外的所有字符 如果需要匹配 . 本身可以用 \.
\d 匹配0-9的数字
\s 匹配任意的空白符,包括空格,制表符(tab),换行符等
\w 匹配字母或数字或下划线或汉字
\b 表示单词边界,出现第一个位置
^ 脱字符,匹配输入字符串的开始的位置,起始位置满足条件才返回,不然为None
$ 匹配输入字符串的结束位置,和^相反
与之对应的 \D \S \W \B 大写与他们的小写作用相反,用()来分组
{M,N} M和N为非负整数,其中M<=N 表示前面的匹配M~N 次,在这个范围呢往多匹配 {M,} 表示需要匹配M次 {,N} 等价于{0~N} {N} 表示需要匹配N次 * 匹配前面的子表达式0次或多次,等价于{0,} + 匹配前面的子表达式一次或多次,等价于{1,} ? 匹配前面的子表达式0次或1次,等价于{0,1} 注: *? +? {M,N}? 表示贪婪与懒惰,往少取
[] 字符类,将要匹配的一类字符集放在[]里面,表示或的意思。例如:[. ? * () {}] 匹配里面的这些字符;[0-9] 匹配0到9的数字相当于\d ; [^\d] 匹配除数字以外的字符,相当于\D ; [a-z] 匹配所有的小写字母[^a-z] 匹配非小写字母 | 相当于或分支条件 例:A|B 匹配字母A或B与[AB]是一样的
() 分组,将要匹配的一类字符用括号, 例 : (\d){3} 匹配一个三位数 ; a(bc)* 匹配一个a和0个或多个bc ; a(b|c)匹配ab或ac
re.I
使匹配对大小写不敏感
re.L
做本地化识别(locale-aware)匹配
re.M
多行匹配,影响 ^ 和 $
re.S
使 . 匹配包括换行在内的所有字符
re.U
根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X
该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
使匹配对大小写不敏感
re.L
做本地化识别(locale-aware)匹配
re.M
多行匹配,影响 ^ 和 $
re.S
使 . 匹配包括换行在内的所有字符
re.U
根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
re.X
该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。
流程控制语句
if语句
单项分支
if 条件表达式:
code1
code2
code1
code2
当条件表达式成立,返回True,执行对应的代码块,反之不执行。
双项分支
if 条件表达式:
code1
code2
else:
code3
code4
code1
code2
else:
code3
code4
如果条件表达式成立,执行if对应代码块。
如果条件表达式不成立,执行else对应的代码块。
如果条件表达式不成立,执行else对应的代码块。
多项分支
if 条件表达式1:
code1
code2
elif 条件表达式2:
code1
code2
elif 条件表达式3:
code1
code2
else:
code1
code2
code1
code2
elif 条件表达式2:
code1
code2
elif 条件表达式3:
code1
code2
else:
code1
code2
如果条件表达式1成立,返回True,执行对应代码块,反之则向下执行
直到最后,任何条件都不满足,执行else。
直到最后,任何条件都不满足,执行else。
循环结构 while|for
while 循环
while 条件表达式:
code1
code2
code1
code2
while 循环中,满足条件便执行,不满足结束。
循环控制
break 结束循环,可以设置条件,当满足条件时结束循环
continue 跳出当前循环,开始下一轮循环,同样可以设置条件
pass 占位符,使程序完整。
else 在while循环中一样可以接else,在while执行完后执行else,但是while中是break结束的循环不会执行else
for循环
for循环的作用:遍历、循环、迭代
for 变量 in 可迭代的对象:
code1
code2
code1
code2
range对象
range(开始值,结束值,步长)
结束值本身取不到,取到结束值之前的那个数
循环控制中与while中一样,使用break和continue
总结
1)while: 较为复杂的逻辑
2)for : 数据的遍历
3)while 和 for 部分代码可相互转换
2)for : 数据的遍历
3)while 和 for 部分代码可相互转换
六大数据类型
不可变类型
数值
数据类型
整数型
小数形式的字符串不能通过int()转化为int型
浮点型
小数形式和整数形式的字符串可以通过float()转化为float型
复数型
布尔
取值
false
true
逻辑运算
and &
or |
not ~
运算
和数值类型计算
字符串类型计算
数值运算
算术运算
比较运算
复合赋值运算
计算函数
内置函数
abs(x)取绝对值
max()最大值
min()最小值
round()四舍五入
pow(x,y)求幂
math计算库
fabs()
ceil()
floor()
exp()
sqrt()
log10(x)
log(x,y)
modf()
字符串
字符串定义
“ ”
str()
可以使用str将其他类型对象转化为字符串
字符串方法
大小写字母变换
capitalize
首字母大写
title
每个单词首字母大写
upper
所有字母大写
lower
所有字母小写
swapcase
字母大小写互换
检索
len()
计算字符串长度
str.startswith("字符")/endswith()
检查字符串是否以某字符开始或者结尾
find()/rfind()
返回从左边开始第一次出现该字符的索引值,如果没有找到返回-1
index()/rindex()
返回从左边开始第一次出现该字符的索引值,如果没有找到则报错
count()
计算字符串中某个字符出现的次数
isupper
判断字符串是否都是大写
islower
判断字符串是否都是小写
isdecimal
判断字符串是否以数字组成
ljust
填充字符串,原字符串居左,默认填充空格
center
填充字符串,原字符串居中,默认填充空格
rjust
填充字符串,原字符串居右,默认填充空格
zfill
返回长度为 width 的字符串,原字符串右对齐,前面填充0
strip
默认去掉首尾两边空白符
rstrip
去掉右边某个字符,默认空白符
lstrip
去掉左边某个字符,默认空白符
replace
字符串替换
replace(“被替换字符或字符串”,“替换字符或字符串”)
str.replace(a,b,替换次数)
用b替换字符串中所有a
分割
str.split("分隔符",分割符号数量)
默认以特殊字符(空格,换行符等)分割
splitlines()
按行分割,参数keepend取false不显示换行符,取true显示换行符
partition()
以str为分隔符,分割成3部分,str前,str和str后
rsplit
从右向左按某字符切割字符串,可指定切割次数
字符串的拼接
直接用 +
格式化字符串 %s 例:'我是%s' % 桂子
%c 格式化ASCII字符
%d 格式化整数
%f 格式化小数
%o 格式化无符号八进制
%x 格式化无符号十六进制
%e 用科学记数法格式化定点数
格式化的辅助运算符
- 用作左对齐 例:'%-10.f' % 1.2223456
+ 用在正数前面显示加号 例:'%+d'% 255
0 显示的数字前面填充‘0’而不是默认的空格 例:‘%010.f’% 3.141596
m.n m是显示的最小长度,当m大于格式化位数时才起作用显示m位,n是显示的小数的位数 例'%10.3f'% 3.141596
注:%s 是通用的,能匹配所有类型
''.join() 括号里是元祖和列表
'{}{}'.format()
字符串格式化
进制转换等特殊符号的使用
:d
整型占位符(要求数据类型必须为整型)
:2d 占用两位,不够用空格来补,默认居右
可用> < ^来调整位置
print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
:f
浮点型占位符(要求数据类型必须为浮点型)
:.2f 可保留小数点后两位
:s
字符串占位符(要求数据类型必须为字符串)
:,
金钱占位符
将一堆纯数字字符串切割为三位一组
str.format格式化
'{}的年龄是{}岁{}'.format('小哥哥', 20 ,'!')
'{2}的年龄是{0}岁{1}'.format('小哥哥', 20, '!')
'{name}的年龄是{age}'.format(age=20,name='小哥哥')
元组
生成元组
tuple()
()生成
不依赖于"()",而是以","为重要标识
元组的切片和索引
tuple[:] # 显示元组中所有值
tuple[0]#输出第一个值
tuple[0]#输出第一个值
元组对象的方法
max(tuple)#返回最大值
min(tuple)#返回最小值
len(tuple) #元组长度
可变类型
列表
列表的定义
list()
list可以把字符串类型转化为列表
[]
遍历列表每一个元素
for var in list:
for i in range(len(list)):
随机取值
choice(list)#随机选择一个元素
sample(list,n)#随机选择n个元素
索引
list[index]#根据索引找对应元素
list.index(a)#返回某个值的索引
list.index(max(list))#返回最大值的索引
list.index(min(list))#返回最小值的索引
list.index(min(list))#返回最小值的索引
列表的切片
[start:end:step]
步长为正数时,从左→右切片
步长为负数时,从右→左切片
排序
list.sort()
顺序,改变原列表
list.reverse()
倒序,改变原列表
sorted(list)
不改变原列表
增
list.append(元素)
每次只能添加一个元素
list_1.extend(list_2)
合并两个表,还可以通过"+"合并多个列表
list.insert(索引值,要插入的元素)
根据偏移量将元素插入到指定的位置
删
del命令
del list[start:end:step]
删除列表中指定位置的元素(一个或多个)
list.clear
list.pop([offset])
返回指定位置的元素,同时在列表中删除该元素
list.remove(元素)
改
list[2] = 'new value'
字典
创建字典
dict2 = dict.fromkeys(dict1)
dict2完全复制dict1
dict2 = dict.fromkeys(dict1,8)
dict2完全复制dict1的键,默认值为8
dict = {'a':[1,2,3],'b':['x','y','z']}
遍历
#循环所有key
1. for item in dict:
2. for item in dict.keys():
1. for item in dict:
2. for item in dict.keys():
for item in dict.values():#循环所有value
for k,v in dict.items():#循环所有键和值
增
dict[键名]=值
dict.setdefault('新键名',值)
dict1.update(dict2) ,把2中的键值对增加到字典1中,如果2中的键和1中的键重复,会覆盖1中的键值对,如果不重复,则会添加到1中
dict1.update({k1:v1,k2:v2})
删
del 字典名['键名']
删除指定键,一次只能删除一个键值对
del 字典名
删除字典
字典名.clear()
删除字典中所有键值对
字典名.pop('键名')
删除指定键,返回删除的键值
字典名.popitem()
随机删除一对键值对,并返回该键值对,一般是最后一对
改
dict[key]=new.value
提取字典中要修改的对应的键,赋予key一个新的值,如果字典中没有这个键,则会把这个键值对添加到字典中
查
字典名['键']
返回该键对应的值
字典名.get('键',alter_output)
返回该键对应的值,若键不存在,则返回第二个参数
字典名.keys()
返回包含所有键的列表
字典名.values()
返回包含所有值的列表
字典名.items()
以元组组成的列表返回包含所有键值对的列表
集合
集合是不重复的有序序列,会自动排序,筛除重复值
创建集合
set()
{}
花括号创建集合
set()
集合具有自动排序和去重的功能
stockSet = set()
stockSet.update(['a','hah','east'])
stockSet = set()
stockSet.update(['a','hah','east'])
增
set.add(新元素)
set.update(新元素)
删
#删除指定元素
set.remove('元素')
set.discard('元素')
set.remove('元素')
set.discard('元素')
set.pop() 随机删除一个元素并返回这个元素
set.clear() 清空集合
集合相关操作
intersection
&
交集
difference
-
差集
union
|
并集
symmetric_difference
^
对称差集
issubset
<
子集
issuperset
>
父级
isdisjoint
不相交
冰冻集合
frozenset
集合冰冻后只能进行交差并补,不能增删
深浅拷贝
浅拷贝
浅拷贝生成的变量不受原变量更改的影响
浅拷贝的两种方法
import copy
a.copy()
a.copy()
b=a.copy() 浅复制,内容相同,id不同
深拷贝
如果是容器类型的数据,深拷贝可以拷贝多级容器
深拷贝方法
c=deepcopy(a)
函数
基本概念
函数基本格式
定义函数
def func():
code1
code2
调用函数
func()
函数命名规则
字母数字下划线,首字符不能为数字。
严格区分大小写,且不能使用关键字。
函数命名有意义,且不能使用中文。
大驼峰命名法
每个单词首字母大写(定义类:面向对象)
小驼峰命名法
除了第一个单词首字符小写之外,剩下每个单词首字符大写
函数参数
形参
形式参数,在函数的定义处
普通形参
通过定义变量按顺序将实参传参
默认形参
形参上面有默认值,为默认形参
普通收集形参
专门用来收集多余没人要的普通实参
*args
命名关键字形参
专门用来收集多余的没人要的关键字实参
**kwargs
关键字收集形参
两种定义方式
def func(a,b,*,c) c是命名关键字
def func(*args,c,**kwargs) c是命名关键字参数
实参
普通实参
定义具体数据并传向形参
关键字实参
关键字实参是对具体的某个参数赋值,具体的顺序可以打乱。
区分默认形参和关键字实参
默认形参在函数的定义处
关键字实参在函数的调用处
关键字实参在函数的调用处
*和**的用法
*和** 在函数的定义处,用来做收集操作,打包
*和** 在函数的调用处,用来做打散操作,解包
*和** 在函数的调用处,用来做打散操作,解包
参数定义的顺序
普通参数 -> 默认参数 -> 普通收集参数 -> 命名关键字参数 -> 关键字收集参数
return返回值
return + 六大标准数据类型 还有类和对象,函数
如果不定义return,默认返回的是None
在执行完return之后,立刻终止函数,后面的代码不执行
如果不定义return,默认返回的是None
在执行完return之后,立刻终止函数,后面的代码不执行
局部变量和全局变量
作用域
作用的范围
局部变量
函数内部定义的变量(在函数内部定义的变量)
局部变量作用域:在函数内部
全局变量
在函数外部定义的或者使用global在函数内部定义
全局变量作用域:横跨整个文件
可以使用global关键字在函数内部定义一个全局变量
也可以使用global关键字在函数内部修改全局变量
也可以使用global关键字在函数内部修改全局变量
函数名的使用
函数可销毁
del +函数名
函数名可作为容器变量元素
函数名可以作为函数的参数
函数名可作为函数的返回值
return +函数名
高阶函数
迭代器
什么是迭代器?
迭代器指的是迭代取值的工具,迭代是一个重复的过程,每次重复都是基于上一次的结果而继续的
迭代器的特征
不依赖于索引,而通过next指针迭代所有数据,一次只取一个值,大大节省空间
可迭代对象
容器类型数据、range对象、迭代器
如何定义一个迭代器
lst = [1,2,3,4,5]
it = iter(lst)
print(it,type(it))
it = iter(lst)
print(it,type(it))
如何判断一个迭代器
如果it中含有iter和next两种魔术方法,那么其类型为迭代器
Iterator
如何调用一个迭代器
用next调用,next在调用迭代器中的数据时,是单向不可逆,一条路走到黑的过程
map
语法
map(func,Iterable)
功能
把Iterable中的数据一个一个拿出来,扔到func中做处理
把处理后的结果放到迭代器中,最后返回迭代器
把处理后的结果放到迭代器中,最后返回迭代器
参数
func:自定义函数
Iterable:可迭代性数据(容器类型数据、range对象、迭代器)
Iterable:可迭代性数据(容器类型数据、range对象、迭代器)
返回值
迭代器
filter
语法
filter(func,iterable)
功能
return True 当前这个数据保留
return False 当前这个数据舍弃
return False 当前这个数据舍弃
参数
func : 自定义函数
iterable : 可迭代型数据(容器类型数据,range对象,迭代器)
iterable : 可迭代型数据(容器类型数据,range对象,迭代器)
返回值
迭代器
reduce
语法
reduce(func,iterable)
功能
计算数据
参数
func : 自定义函数
iterable : 可迭代型数据(容器类型数据,range对象,迭代器)
iterable : 可迭代型数据(容器类型数据,range对象,迭代器)
返回值
计算之后的结果
sorted
语法
sorted(iterable,key=函数,reverse=False)
功能
排序
参数
iterable(容器类型数据,range对象,迭代器)
key 指定 自定义函数或 内置函数
reverse : 代表升序或者降序 , 默认是升序(从小到大排序) reverse=False
key 指定 自定义函数或 内置函数
reverse : 代表升序或者降序 , 默认是升序(从小到大排序) reverse=False
返回值
排序后的结果
与sort的区别
(1) sorted可以排序一切容器类型数据, sort只能排列表
(2) sorted返回的是新列表,sort是基于原有的列表进行修改
(3) 推荐使用sorted
(2) sorted返回的是新列表,sort是基于原有的列表进行修改
(3) 推荐使用sorted
匿名函数 lambda
lambda 可以用于简单的函数简写
filter(判断条件,参数) 过滤器
map(函数,迭代器)
reduce ()
推导式
列表推导式
列表推导式在逻辑上等价于一个循环语句,只是形式上更加简洁
列表推导式在逻辑上等价于一个循环语句,只是形式上更加简洁
单循环推导式
语法:[val for val in Iterable]
语法:[val for val in Iterable]
带有判断条件的单循环推导式
语法:[val for val in Iterable if val>0 else 0]
语法:[val for val in Iterable if val>0 else 0]
双循环推导式
[num for elem in vec for num in elem]
[num for elem in vec for num in elem]
带有判断条件的双循环推导式
[num for elem in vec for num in elem if cond1]
[num for elem in vec for num in elem if cond1]
zip
语法
zip(iterable, … …)
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
功能
将多个iterable中的值,一个一个拿出来配对组成元组放入迭代器中
enumerate
语法
enumerate(iterable,start=0)
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
功能
枚举 ; 将索引号和iterable中的值,一个一个拿出来配对组成元组放入迭代器中
集合_字典推导式
集合推导式
语法:{val for val in Iterable}
字典推导式
语法:{k,v for k,v in Iterable}
生成器
什么是生成器
生成器本质是迭代器,允许自定义逻辑的迭代器
生成器和迭代器的区别
迭代器本身是系统内置的.重写不了.而生成器是用户自定义的,可以重写迭代逻辑
创建生成器的两种方式
生成器表达式 (里面是推导式,外面用圆括号)
生成器函数 (用def定义,里面含有yield)
yield与return的共同点及区别点
共同点
执行到这句话都会把值返回出去
区别点
yield每次返回时,会记住上次离开时执行的位置 , 下次在调用生成器 , 会从上次执行的位置往下走, 而return直接终止函数,每次重头调用.
send
next与send区别
next 只能取值
send 不但能取值,还能发送值
send 不但能取值,还能发送值
注意点
第一个 send 不能给 yield 传值 默认只能写None
最后一个yield 接受不到send的发送值
send 是给上一个yield发送值
最后一个yield 接受不到send的发送值
send 是给上一个yield发送值
yield from
可将一个可迭代对象变成一个迭代器返回
运算符
算术运算符
加
+
减
-
乘
*
除
/
整除
//
求余
%
求幂
**
比较运算符
等于
==
大于
>
小于
<
大于等于
>=
小于等于
<=
不等于
!=
赋值运算符
=
+=
c += a 等效于 c = c + a
-=
c -= a 等效于 c = c - a
*=
c *= a 等效于 c = c * a
/=
c /= a 等效于 c = c / a
//=
c //= a 等效于 c = c // a
%=
c %= a 等效于 c = c % a
**=
c **= a 等效于 c = c ** a
逻辑运算符
and &
or |
not ~
其他运算符
成员运算符
in
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("1 - 变量 a 在给定的列表中 list 中")
else:
print ("1 - 变量 a 不在给定的列表中 list 中")
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("1 - 变量 a 在给定的列表中 list 中")
else:
print ("1 - 变量 a 不在给定的列表中 list 中")
not in
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( b not in list ):
print ("2 - 变量 b 不在给定的列表中 list 中")
else:
print ("2 - 变量 b 在给定的列表中 list 中")
b = 20
list = [1, 2, 3, 4, 5 ]
if ( b not in list ):
print ("2 - 变量 b 不在给定的列表中 list 中")
else:
print ("2 - 变量 b 在给定的列表中 list 中")
身份运算符
is
x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
is not
x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。
位运算符
&
按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0
|
按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。
^
按位异或运算符:当两对应的二进位相异时,结果为1
~
按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1。~x 类似于 -x-1
<<
左移动运算符:运算数的各二进位全部左移若干位,由"<<"右边的数指定移动的位数,高位丢弃,低位补0。
a << 2 输出结果 240 ,二进制解释: 1111 0000
a << 2 输出结果 240 ,二进制解释: 1111 0000
>>
右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,">>"右边的数指定移动的位数
a >> 2 输出结果 15 ,二进制解释: 0000 1111
a >> 2 输出结果 15 ,二进制解释: 0000 1111
文件操作
文件操作
文件的写入
打开文件
fp = open("文件名",mode="w",encoding="utf-8")
写入文件
fp.write()
关闭文件
fp.close()
文件的读取
打开文件
fp = open("文件名",mode="r",encoding="utf-8")
读取文件
res=fp.read()
print(res)
关闭文件
fp.close()
存储二进制字节流
wb
读取二进制字节流
rb
文件扩展模式
read
读取字符个数(里面参数代表字符个数)
seek
调整指针位置(里面参数代表字节个数)
seek(0):将光标移动到文件开头
seek(0,2):将光标移动到文件结尾
tell
当前光标左侧所有的字节数(返回字节数)
r+
先读后写
w+
可读可写
会清空文件,重新写入
a+
可读可写,追加
with语法
with open("文件名",mode="模式",encoding="字符编码") as fp:
r 只读 默认
w 以写入的方式打开文件,会覆盖已存在的文件
a 以写入的方式打开文件,如果文件存在会追加写入
b 以二进制模式打开文件,例wb rb
文件对象的方法属性
f.close() 关闭文件
f.read() 读取文件的所有字符,也设置读取字符的个数
f.readline() 从文件中读取并返回一行,也可设置读取字符个数
f.readlines() 返回的是一个列表
f.write('内容') 将字符串写入文件
f.flush() 写入后刷新
f.writeline(seq) 向文件写入字符串序列seq,seq是返回字符串的可迭代对象
f.writelines(x) x可以是一个列表
f.seek(offset,form) 在文件中移动文件指针,从from(默认起始位为0,1代表当前位置,为代表末尾)偏移offset个字节
f.fell() 返回当前指针在文件夹的位置
with open() as f 自动关闭
use case
FAQ
Q: How to set up the data science environment
A:
1. software installation
open IT Service Portal-->Add/Remove Software-->install hadoop connectivity & Anaconda Python
2. config ODBC
open ODBC Data Sources (64-bit)-->User DSN-->Add-->Cloudera ODBC Driver for Impala-->Finish-->Config
Data Source Name:SZHP1
Description:SZHP1
Host:szh-iplb-rbap.apac.bosch.com
Port:21050
Database:impala
Mechanism:Kerberos
Realm:RB-AE-SZHP1.BDPS.BOSCH-ORG.COM
SSL Options:enable SSL
Advanced Options:set Socket timeout as 0
click test to verify ODBC connection,success means configuration finished, click OK to save change.
1. software installation
open IT Service Portal-->Add/Remove Software-->install hadoop connectivity & Anaconda Python
2. config ODBC
open ODBC Data Sources (64-bit)-->User DSN-->Add-->Cloudera ODBC Driver for Impala-->Finish-->Config
Data Source Name:SZHP1
Description:SZHP1
Host:szh-iplb-rbap.apac.bosch.com
Port:21050
Database:impala
Mechanism:Kerberos
Realm:RB-AE-SZHP1.BDPS.BOSCH-ORG.COM
SSL Options:enable SSL
Advanced Options:set Socket timeout as 0
click test to verify ODBC connection,success means configuration finished, click OK to save change.
Q: How to change default path for jupyter file?
A:
1. open Anaconda Prompt (Anaconda3)-->input "jupyter notebook --generate-config"
2. create new folder in C: for jupyter(C:/jupyter_notebooks)
3. go to C:\Users\<your NT account>\.jupyter-->open jupyter_notebook_config.json
-->update c.NotebookApp.notebook_dir="C:/jupyter_notebooks"
4.open Anaconda Prompt (Anaconda3)-->input "jupyter notebook"
1. open Anaconda Prompt (Anaconda3)-->input "jupyter notebook --generate-config"
2. create new folder in C: for jupyter(C:/jupyter_notebooks)
3. go to C:\Users\<your NT account>\.jupyter-->open jupyter_notebook_config.json
-->update c.NotebookApp.notebook_dir="C:/jupyter_notebooks"
4.open Anaconda Prompt (Anaconda3)-->input "jupyter notebook"
Q: Why I failed to connect to hadoop via python?
A:
Go to Anaconda 3 on you Windows start menu and click on “Anaconda Prompt”
Once there, enter:
conda create --name py36 python=3.6 pyodbc jupyter pandas numpy (and all other packages you might need)
then activate the environment with:
conda activate py36
then start jupyter notebook with:
jupyter-notebook
Go to Anaconda 3 on you Windows start menu and click on “Anaconda Prompt”
Once there, enter:
conda create --name py36 python=3.6 pyodbc jupyter pandas numpy (and all other packages you might need)
then activate the environment with:
conda activate py36
then start jupyter notebook with:
jupyter-notebook
Tools
jupyter notebook
theme/nbextensions
theme/plugin installation
#安装nbextensions
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
#安装主题
pip install jupyterthemes
jt -t grade3 -f fira -fs 13 -cellw 90% -ofs 11 -dfs 11 -T -N
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
#安装主题
pip install jupyterthemes
jt -t grade3 -f fira -fs 13 -cellw 90% -ofs 11 -dfs 11 -T -N
theme install parameters
好用的插件
Table of Contents
目录,可以将所有的heade标题栏收集起来,只对于已经运行的markdown类型的标题有效.通过目录可以进入指定链接.
目录,可以将所有的heade标题栏收集起来,只对于已经运行的markdown类型的标题有效.通过目录可以进入指定链接.
Variable Inspector
这是一个查看变量的插件,可以查看变量名、类型,大小,形状和值。
这是一个查看变量的插件,可以查看变量名、类型,大小,形状和值。
Hinterland
代码自动补全,选中
代码自动补全,选中
Codefolding
折叠代码(包括Python依据缩进折叠、其他代码依据方括号折叠、依据注释折叠)
折叠代码(包括Python依据缩进折叠、其他代码依据方括号折叠、依据注释折叠)
ExcecuteTime
在代码模块最后计算该模块的计算时间和运行结束时间,美观实用
在代码模块最后计算该模块的计算时间和运行结束时间,美观实用
Spellchecker
对 markdown 单元中的内容进行拼写检查
对 markdown 单元中的内容进行拼写检查
code_prettify
代码美化,先配置环境: pip install yapf
代码美化,先配置环境: pip install yapf
shortcut
shift +enter
运行当前代码
esc ; m
进入标记模式,生成标题
esc ; b/a
在当前模块下面或者上方增加一个模块
ctrl+shift+-
按鼠标位置拆分当前代码模块
shift+m
合并选中的代码模块
ctrl+/
将多行内容同时改为注释
Pycharm
Preparing Data
Pandas
输出设置
#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#设置value的显示长度为100,默认为50
pd.set_option('max_colwidth',100)
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#设置value的显示长度为100,默认为50
pd.set_option('max_colwidth',100)
数据存储与提取
导入
pd.read_csv('文件全路径')
#路径存在中文时
file = open(r'文件全路径')
df = pd.read_csv(file)
#路径存在中文时
file = open(r'文件全路径')
df = pd.read_csv(file)
csv、tsv、txt
pd.read_sql()
sql
#获取所有表的字段
dic = {}
for i in process_tables:
content_table = pd.read_sql("DESCRIBE "+database+"."+i , conn)
columns = []
for j, k in content_table.iterrows():
column_name= k["name"]
columns.append(column_name)
dic[i] = columns
for i in process_tables:
content_table = pd.read_sql("DESCRIBE "+database+"."+i , conn)
columns = []
for j, k in content_table.iterrows():
column_name= k["name"]
columns.append(column_name)
dic[i] = columns
获取指定数据库所有表名
table = "SHOW tables IN "+database
tables = pd.read_sql(table,conn)
tables = pd.read_sql(table,conn)
pd.read_excel('文件全路径')
xlsx、xls、xlsm
pd.read_json()
json
df = read_xlsb()
xlsb
import pyxlsb
def read_xlsb(file_path):
list_row = []
list_accumulate = []
# xlsb
if file_path[-5:] == '.xlsb':
wb = pyxlsb.open_workbook(file_path)
print(wb.get_sheet(wb.sheets[0]).rows())
'''
# 循环遍历所有sheet
for i in range(len(wb.sheets)):
sheet_row = wb.get_sheet(wb.sheets[i]).rows()
for sr in sheet_row:
for s in sr:
list_row.append(s.v)
list_accumulate.append(list_row)
list_row=[]
'''
# 遍历选定sheet
sheet_row = wb.get_sheet(1).rows()
for sr in sheet_row:
for s in sr:
list_row.append(s.v)
list_accumulate.append(list_row)
list_row = []
return list_accumulate
def read_xlsb(file_path):
list_row = []
list_accumulate = []
# xlsb
if file_path[-5:] == '.xlsb':
wb = pyxlsb.open_workbook(file_path)
print(wb.get_sheet(wb.sheets[0]).rows())
'''
# 循环遍历所有sheet
for i in range(len(wb.sheets)):
sheet_row = wb.get_sheet(wb.sheets[i]).rows()
for sr in sheet_row:
for s in sr:
list_row.append(s.v)
list_accumulate.append(list_row)
list_row=[]
'''
# 遍历选定sheet
sheet_row = wb.get_sheet(1).rows()
for sr in sheet_row:
for s in sr:
list_row.append(s.v)
list_accumulate.append(list_row)
list_row = []
return list_accumulate
导出
df.to_csv('C:/Users/xx/Result.csv',sep=',')
df.to_excel()
数据检查
选择子集--df切片
testdf3.iloc[0] # pandas series
testdf3.iloc[[0]] # dataframe
testdf3.iloc[[0]] # dataframe
取一行
testdf3[['A']] #单独一列
testdf3.loc[:,['A']] # 同上,但比较复杂,一般不用
testdf3.iloc[:,[0]] # 同上,可以在不知道列名的时候用
testdf3.loc[:,['A']] # 同上,但比较复杂,一般不用
testdf3.iloc[:,[0]] # 同上,可以在不知道列名的时候用
testdf3[2:3] # data frame
testdf3.iloc[2:3]
testdf3.iloc[2:3]
取连续的某几行
testdf3.iloc[[1,3]]
取不连续的多行
testdf3[['A','C']] # DF, 指定某几列,直接用列名
testdf3.loc[:,['A','C']] # 同上,但比较复杂,一般不用
testdf3.iloc[:,[0,2]] # 同上,可以在不知道列名的时候用
testdf3.loc[:,['A','C']] # 同上,但比较复杂,一般不用
testdf3.iloc[:,[0,2]] # 同上,可以在不知道列名的时候用
testdf3.loc[:,'A':'D'] #指定连续列,用列名
testdf3.iloc[:,0:4] # 指定连续列,用数字
testdf3.iloc[:,0:4] # 指定连续列,用数字
testdf3.iloc[[1,3],[0]] # 取行索引为1或3,列索引为0的结果
testdf3.iloc[[1,3],1:3] # 取行索引为1或3,列索引为1和2的结果
testdf3.iloc[[1,3],[1,3]]# 取行/列索引为1或3的结果
testdf3.iloc[[1,3],1:3] # 取行索引为1或3,列索引为1和2的结果
testdf3.iloc[[1,3],[1,3]]# 取行/列索引为1或3的结果
testdf3.loc[[1,3],["A","D"]]#取行索引为1或3,列名为A和D的值
df3.loc[:,(df3>1).any()]#Select cols with any vals >1
查看数据
初步查看:
df.head(n)#前n行
df.tail(n)#后n行
df.head(n)#前n行
df.tail(n)#后n行
统计信息,是否有异常值:df.describe()
查看一列:df['列名']
查看一列前几行:df['列名'][:n]
查看多列:df[['列1','列2']]
where过滤:df[df['列名']>condition]
查看一列前几行:df['列名'][:n]
查看多列:df[['列1','列2']]
where过滤:df[df['列名']>condition]
重命名列名
导入文件时改
df=pd.read_csv('path',name=['name1','name2'])
导入文件后改
列:df.rename(columns={'原列1':'新列1'},inplace=True/False)
行:df.rename(index={'原行1':'新行1'},inplace=True/False)
行:df.rename(index={'原行1':'新行1'},inplace=True/False)
df增删改查
df = pd.Dataframe(ndarray/list/dict,columns=('a','b')
df['new'] = a#新增一列
df.loc['row'] = a#新增一行
df.append(df2,ignore_index=True)#纵向合并
df.drop(columns=['a','b'],axis=1)#删除a,b列
df.drop(0,axis=0)#删除索引为0的行
df.rename(columns={col1:col1_after,col2:col2_after})
df.columns=[v1,v2,v3,v4]
df.columns=[v1,v2,v3,v4]
修改DataFrame的列名
df['a'].isin([k1,k2,k3])
对DataFrame的数据进行条件筛选
df3.loc[:,(df3>1).any()] #选择存在值大于1的列
df3.loc[:,(df3>1).all()] #选择所有值都大于1的列
df3.loc[:,(df3>1).all()] #选择所有值都大于1的列
s.where((s > 0) & (s<4))
.where()
将不符合条件的值替换掉成指定值,相当于执行了一个if-else
将不符合条件的值替换掉成指定值,相当于执行了一个if-else
# 若salary<=40,则保持原来的值不变
# 若salary大于40,则设置为40
data['salary'].where(data.salary<=40,40)
# 若salary大于40,则设置为40
data['salary'].where(data.salary<=40,40)
df6.query('second > first')
>>> df[(df.Country.isin(df2.Type))] #Find same elements
>>> df[~(df.Country.isin(df2.Type))] #Find different elements
>>> df3.filter(items=”a”,”b”]) #Filter on values
>>> df.select(lambda x: not x%5) #Select specific elements
>>> df[~(df.Country.isin(df2.Type))] #Find different elements
>>> df3.filter(items=”a”,”b”]) #Filter on values
>>> df.select(lambda x: not x%5) #Select specific elements
统计方法
统计
df.describe()
生成描述性统计汇总,包括数据的计数和百分位数,有助于了解大致的数据分布
df.shape
(行,列)
df.info()
打印所用数据的一些基本信息,包括索引和列的数据类型和占用的内存大小。
df.value_counts()
统计分类变量中每个类的数量,比如company中各个公司都有多少人
df['company'].value_counts()
df['company'].value_counts()
df.count()
计数
df['a'].nunique()
a列有多少不同值
df['a'].unique()
a列所有不同值
df.mean()
均值
df.sum()
求和
df.size()
dh大小(行,列)
df.std()
标准差
df.median()
中位数
df.quantile(n)
求任一分位数,n取0.1,0.3
df.var()
方差
df.min()
最小值
df.max()
最大值
df.nth()
返回第n行
数据清洗
数据类型转化
导入数据时改变
data = pd.read_csv('path',dtype={'列1':int})
导入数据后改变
df['列1'].astype(数据类型)
字符串转为数值
df.loc['col'] = pd.to_numeric(df.loc['col'],errors='coerce')
只转换能转换的,不能转换的赋值为NaN
只转换能转换的,不能转换的赋值为NaN
数据规整化
大小写转换
全转成大写
df['col'].map(str.upper)
全转成小写
df['col'].map(str.lower)
首字母大写
df['col'].map(str.title)
空格
去除左边空值
df['col'].map(str.lstrip)
去除右边空值
df['col'].map(str.rstrip)
去除两边空值
df['col'].map(str.strip)
离群点和异常值
查找:df.describe()统计分析,最大值最小值中位数
plt.bar()箱线图
plt.bar()箱线图
处理:df.replace({'col':(异常值)},新值)
数据缺失
索引
选择缺失值
>>> df3.loc[:,df3.isnull().any()]#选择存在缺失值的列
>>> df3.loc[:,df3.notnull().all()]# 选择不存在缺失值的列
>>> df3.loc[:,df3.notnull().all()]# 选择不存在缺失值的列
计算数量
df.isnull().sum()
处理
删除数据dropna()
根据缺失比例删除行
有就删除:df.dropna()
全部缺失才删除:df.dropna(how='all')
至少n个才删除:df.dropna(thresh=n)
某个/几个列值缺失删除:df.dropna(subset=['col1','col2'])
根据缺失比例删除列
有就删除:df.dropna(axis=1)
全部缺失才删除:df.dropna(how='all',axis=1)
直接删除列
df.drop(['col'],axis=1)
替换数据replace()
>>> df2.replace("a", "f") #值替换
填充数据fillna()
>>> df.fillna(0, inplace=True) #固定值填充
>>> df.fillna(method='ffill', inplace=True) #前面的值填充
>>> df.fillna(method='bfill', inplace=True) #后面的值填充
>>> df['col'].fillna(df.mean(), inplace=True)#均值填充
>>> df.fillna(method='ffill', inplace=True) #前面的值填充
>>> df.fillna(method='bfill', inplace=True) #后面的值填充
>>> df['col'].fillna(df.mean(), inplace=True)#均值填充
使用默认值
空字符串
df['col'].fillna('')
特殊值0/1
df['col'].fillna(0, inplace=True)
使用特征统计值
(缺失数据较少)
(缺失数据较少)
mean()均值
df['col'].fillna(df.mean(), inplace=True)
from sklearn.preprocessing import Imputer
nan_model = Imputer(miss_values='nan', strategy='mean', axis=0)
nan_result = nan_model.fit_transform(df)
nan_model = Imputer(miss_values='nan', strategy='mean', axis=0)
nan_result = nan_model.fit_transform(df)
mode()众数
df['col'].fillna(df.mode(), inplace=True)
from sklearn.preprocessing import Imputer
nan_model = Imputer(miss_values='nan', strategy='most_frequent ', axis=0)
nan_result = nan_model.fit_transform(df)
nan_model = Imputer(miss_values='nan', strategy='most_frequent ', axis=0)
nan_result = nan_model.fit_transform(df)
median()中位数
df['col'].fillna(df.median(), inplace=True)
from sklearn.preprocessing import Imputer
nan_model = Imputer(miss_values='nan', strategy='median ', axis=0)
nan_result = nan_model.fit_transform(df)
nan_model = Imputer(miss_values='nan', strategy='median ', axis=0)
nan_result = nan_model.fit_transform(df)
舍弃或二元化处理
(缺失数据较多)
(缺失数据较多)
非空:df.loc[df.['col'].notnull,'col']=newvalue1
空值:df.loc[df.['col'].isnull,'col']=newvalue2
空值:df.loc[df.['col'].isnull,'col']=newvalue2
插值法
拉格朗日(复用代码)
# 拉格朗日插值法
import scipy.interpolate
from scipy.interpolate import lagrange
def lagrange_fill(dataframe, colname, k=5):
def ployinterp_column(s, n, k=5):
y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 + k))] #取数
y = y[y.notnull()] #剔除空值
return lagrange(y.index, list(y))(n) #插值并返回插值结果
for i, index in enumerate(
dataframe[colname][dataframe[colname].isnull() == True].index):
dataframe[colname][index] = ployinterp_column(dataframe[colname],
i) # todo 返回当前数据的位置
return dataframe
lagrange_fill(df, 'a') #col为实际列名
import scipy.interpolate
from scipy.interpolate import lagrange
def lagrange_fill(dataframe, colname, k=5):
def ployinterp_column(s, n, k=5):
y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 + k))] #取数
y = y[y.notnull()] #剔除空值
return lagrange(y.index, list(y))(n) #插值并返回插值结果
for i, index in enumerate(
dataframe[colname][dataframe[colname].isnull() == True].index):
dataframe[colname][index] = ployinterp_column(dataframe[colname],
i) # todo 返回当前数据的位置
return dataframe
lagrange_fill(df, 'a') #col为实际列名
利用缺失值上下填充
前面的值填充:df.fillna(method='ffill', inplace=True)
后面的值填充:df.fillna(method='bfill', inplace=True)
后面的值填充:df.fillna(method='bfill', inplace=True)
随机森林算法预测
确实字符串:用常见频数类别代替:df['col].value_counts()
重复值
索引
查找重复值:df.duplicated()
df.index.duplicated()
df.index.duplicated()
计算重复值数量:df.duplicated().value_counts()
某列中存在唯一值:df['col'].unique()
处理 -- 删除
df2.drop_duplicates('col', keep='last',inplace=True)
排序
df.sort_values(by=['a','b'],ascending=False)
df.reset_index(drop=True)
索引
df.index = range(1,len(df)+1)
s.reindex(['a','c','d','e','b'])
df = df.reset_index()#默认重置后的索引为0~len(df)-1
df.set_index('col',inplace=True)
df = df.rename(index=str, columns={"Country":"cntry","Capital":"cptl","Population":"ppltn"})
字典字段选择(复用代码)
table2result_columns = {}
for table, column_list in dic.items():
good_columns = []
for col in column_list:
#col.endswith("_result") or
if(col.endswith("_result") or col == 'uniquepart_id' or col == 'result_date' or col == 'location_id' \
or col == 'type_number'):#add only relevant columns
good_columns.append(col)
table2result_columns[table] = good_columns
for table, column_list in dic.items():
good_columns = []
for col in column_list:
#col.endswith("_result") or
if(col.endswith("_result") or col == 'uniquepart_id' or col == 'result_date' or col == 'location_id' \
or col == 'type_number'):#add only relevant columns
good_columns.append(col)
table2result_columns[table] = good_columns
遍历
>>> df.iteritems()# (Column-index, Series) pairs
>>> df.iterrows() # (Row-index, Series) pairs
>>> df.iterrows() # (Row-index, Series) pairs
日期
pd.to_datetime(data, format='%Y%m%d', errors='ignore')
data["trade_date"] = pd.to_datetime(data.trade_date)
从csv文件中导入数据,此时Dataframe中对应的时间列是字符串的形式
从csv文件中导入数据,此时Dataframe中对应的时间列是字符串的形式
df2['Date']= pd.date_range('2000-1-1',periods=6,freq='M')
#yesterday
import datetime
def getYesterday():
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday
import datetime
def getYesterday():
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday
数据转换
类型转换
ndarray = df.values
list = df.values.tolist()
dict = df.to_dict()
df = pd.DataFrame(ndarray)
df = pd.DataFrame(list)
df = pd.DataFrame.from_dict(data, orient='index')
df = pd.DataFrame(list)
df = pd.DataFrame.from_dict(data, orient='index')
list-->str
#字段拼接为字符串
ls = sql_columns[0]
for i in range(1,len(sql_columns)):
str_sql = ','.join(sql_columns[i])
ls.append(str_sql)
process_ls = ','.join(ls)
process_ls
ls = sql_columns[0]
for i in range(1,len(sql_columns)):
str_sql = ','.join(sql_columns[i])
ls.append(str_sql)
process_ls = ','.join(ls)
process_ls
行列变换
df['a'].astype(int)
pd.cut()
将连续变量离散化,比如将人的年龄划分为各个区间
将连续变量离散化,比如将人的年龄划分为各个区间
pd.cut(data.salary,bins = [0,10,20,30,40,50],labels = ['低','中下','中','中上','高'])
pd.cut(data.salary,bins = 5) #把薪水分成5个区间
pd.qcut()
使用分位数进行区间划分
使用分位数进行区间划分
pd.qcut(data.salary,q = 3)
.pivot_table()
pd.pivot_table(df2, values='Value',index='Date',columns='Type'])#Spread rows into columns
.pivot()
df2.pivot(index='Date', columns='Type',values='Value')#Spread rows into columns
Stack / Unstack
>>> stacked = df5.stack() #Pivot a level of column labels
>>> stacked.unstack() #Pivot a level of index labels
>>> stacked.unstack() #Pivot a level of index labels
Melt
>>> pd.melt(df2, id_vars=["Date"],value_vars=["Type", "Value"],value_name="Observations")
#Gather columns into rows
#Gather columns into rows
map()
apply()
applymap()
apply()
applymap()
df['a'].map()
map可以作用于Series每一个元素的
对于Series而言,map可以解决绝大多数的数据处理需求,但如果需要使用较为复杂的函数,则需要用到apply方法。
对于Series而言,map可以解决绝大多数的数据处理需求,但如果需要使用较为复杂的函数,则需要用到apply方法。
data["gender"] = data["gender"].map({"男":1, "女":0})
def gender_map(x):
gender = 1 if x == "男" else 0
return gender
#注意这里传入的是函数名,不带括号
data["gender"] = data["gender"].map(gender_map)
gender = 1 if x == "男" else 0
return gender
#注意这里传入的是函数名,不带括号
data["gender"] = data["gender"].map(gender_map)
df['a'].apply()
df.apply()
df.apply()
apply()方法 可以作用于DataFrame 还有Series
def apply_age(x,bias):
return x+bias
#以元组的方式传入额外的参数
data["age"] = data["age"].apply(apply_age,args=(-3,))
return x+bias
#以元组的方式传入额外的参数
data["age"] = data["age"].apply(apply_age,args=(-3,))
def BMI(series):
weight = series["weight"]
height = series["height"]/100
BMI = weight/height**2
return BMI
data["BMI"] = data.apply(BMI,axis=1)
weight = series["weight"]
height = series["height"]/100
BMI = weight/height**2
return BMI
data["BMI"] = data.apply(BMI,axis=1)
df.applymap()
对DataFrame中的每个单元格执行指定函数的操作
df.applymap(lambda x:"%.2f" % x)
分组与聚合
df.groupby('Gender')
无法调用,输出为
<class 'pandas.core.groupby.groupby.DataFrameGroupBy'>
<class 'pandas.core.groupby.groupby.DataFrameGroupBy'>
通过对DataFrame对象调用groupby()函数返回的结果是一个DataFrameGroupBy对象,而不是一个DataFrame或者Series对象,所以,它们中的一些方法或者函数是无法直接调用的,需要按照GroupBy对象中具有的函数和方法进行调用
df.groupby(['Gender', 'Age'])
无法调用,输出为
<class 'pandas.core.groupby.groupby.DataFrameGroupBy'>
<class 'pandas.core.groupby.groupby.DataFrameGroupBy'>
df.groupby('Gender').get_group('Female')
通过get_group筛选df中满足条件的值并输出
df.groupby('petalwidth')['class'].nunique().to_frame('newcolname')
按照petalwidth分组并计算class列不同值的数量作为新列newcolname
df.groupby('Gender').max()[['Age', 'Score']]
根据性别分组并输出age,score最大值
df.groupby('Gender').agg({'Age':np.median, 'Score':np.sum})
根据性别分组并输出age中位数,score求和
df.groupby('Gender').agg(['mean','sum'])
根据性别分组并输出其他列的均值和求和
data['avg_salary'] = data.groupby('company')['salary'].transform('mean')
对每一条数据求得相应的结果,同一组内的样本会有相同的值,组内求完均值后会按照原索引的顺序返回结果
df.groupby('Gender')['age'].plot(kind='kde', legend=True)
根据性别分组并绘制年龄概率密度分布图
数据合并
join
df1.join(df2, on=None, how=’left’)
默认按索引合并
merge
pd.merge(df1,df2,how='inner',on='key', left_on=None, right_on=None)
concat
pd.concat([data1,data2],ignore_index=True,axis=1,join='inner',keys=['a','b'])
append
s.append(s2)
SK-Learn
Standardization
标准化
标准化
>>> from sklearn.preprocessing import StandardScaler
>>> scaler = StandardScaler().fit(X_train)
>>> standardized_X = scaler.transform(X_train)
>>> standardized_X_test = scaler.transform(X_test)
>>> scaler = StandardScaler().fit(X_train)
>>> standardized_X = scaler.transform(X_train)
>>> standardized_X_test = scaler.transform(X_test)
通过对原始数据进行变换把数据变换到均值为0,方差为1范围内
Normalization
正则化
正则化
>>> from sklearn.preprocessing import Normalizer
>>> scaler = Normalizer().fit(X_train)
>>> normalized_X = scaler.transform(X_train)
>>> normalized_X_test = scaler.transform(X_test)
>>> scaler = Normalizer().fit(X_train)
>>> normalized_X = scaler.transform(X_train)
>>> normalized_X_test = scaler.transform(X_test)
L1正则化: 向量中各元素绝对值之和
L2正则化: 向量中各元素的平方之和
L2正则化: 向量中各元素的平方之和
Binarization
二值化
二值化
>>> from sklearn.preprocessing import Binarizer
>>> binarizer = Binarizer(threshold=0.0).fit(X)
>>> binary_X = binarizer.transform(X)
>>> binarizer = Binarizer(threshold=0.0).fit(X)
>>> binary_X = binarizer.transform(X)
设定一个阈值,使得样本矩阵中大于阈值的元素置换为1;小于或等于阈值置换为0
Encoding Categorical Features
独热编码
独热编码
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
One_encode = OneHotEncoder(sparse = False,drop='first')
label_encode = LabelEncoder()
dic1 = {}
for i in range(0,len(keepcol)):
label_classes = label_encode.fit_transform(df[keepcol[i]])
label_name = [keepcol[i]+'_'+str(Leg_class) for Leg_class in label_encode.classes_]
res = One_encode.fit_transform(df[keepcol[i]].values.reshape(-1,1))
dic = {label_name[j]:res[:, j] for j in range(len(label_name)-1)}
dic1.update(dic)
i += 1
dis_df = pd.DataFrame(dic1)
One_encode = OneHotEncoder(sparse = False,drop='first')
label_encode = LabelEncoder()
dic1 = {}
for i in range(0,len(keepcol)):
label_classes = label_encode.fit_transform(df[keepcol[i]])
label_name = [keepcol[i]+'_'+str(Leg_class) for Leg_class in label_encode.classes_]
res = One_encode.fit_transform(df[keepcol[i]].values.reshape(-1,1))
dic = {label_name[j]:res[:, j] for j in range(len(label_name)-1)}
dic1.update(dic)
i += 1
dis_df = pd.DataFrame(dic1)
将有n种特征值的一个特征变成n个二元的特征,所有二元特征互斥,当某个二元特征为 1 时,表示取对应的这个类别
Imputing Missing Values
缺失值处理
缺失值处理
>>> from sklearn.preprocessing import Imputer
>>> imp = Imputer(missing_values=0, strategy='mean', axis=0)
>>> imp.fit_transform(X_train)
>>> imp = Imputer(missing_values=0, strategy='mean', axis=0)
>>> imp.fit_transform(X_train)
Modeling(Y2021 common module)
模型选择
交叉验证法
分类
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
#分类
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
# 算法审查
models = {}
# ****************************************classification****************************************
models['LR'] = LogisticRegression()#逻辑回归
models['LDA'] = LinearDiscriminantAnalysis()#线性判别分析
models['KNN'] = KNeighborsClassifier()#K近邻
models['CART'] = DecisionTreeClassifier()#决策树
models['NB'] = GaussianNB()#贝叶斯
models['SVM'] = SVC()#支持向量机
models['RFC'] = RandomForestClassifier()#随机森林 max_features = "sqrt"
# 评估算法
results = []
for key in models:
kfold = KFold(n_splits=10, random_state=seed,shuffle=True)
# scoring = ['accuracy','neg_log_loss','roc_auc','f1','f1_micro','f1_macro','f1_weighted'] #分类
cv_results = cross_val_score(models[key], X_train, Y_train, cv=kfold, scoring='accuracy')
results.append(cv_results)
print('%s: %.3f%% (%.3f%%)' %(key, cv_results.mean()*100, cv_results.std()))
from sklearn.model_selection import cross_val_score
#分类
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
# 算法审查
models = {}
# ****************************************classification****************************************
models['LR'] = LogisticRegression()#逻辑回归
models['LDA'] = LinearDiscriminantAnalysis()#线性判别分析
models['KNN'] = KNeighborsClassifier()#K近邻
models['CART'] = DecisionTreeClassifier()#决策树
models['NB'] = GaussianNB()#贝叶斯
models['SVM'] = SVC()#支持向量机
models['RFC'] = RandomForestClassifier()#随机森林 max_features = "sqrt"
# 评估算法
results = []
for key in models:
kfold = KFold(n_splits=10, random_state=seed,shuffle=True)
# scoring = ['accuracy','neg_log_loss','roc_auc','f1','f1_micro','f1_macro','f1_weighted'] #分类
cv_results = cross_val_score(models[key], X_train, Y_train, cv=kfold, scoring='accuracy')
results.append(cv_results)
print('%s: %.3f%% (%.3f%%)' %(key, cv_results.mean()*100, cv_results.std()))
回归
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
#线性回归
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.linear_model import ElasticNet
#非线性回归
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# 算法审查
models = {}
# ****************************************Regression****************************************
#线性
models['LinearR'] = LinearRegression()
models['ridge'] = Ridge()
models['lasso'] = Lasso()
models['EN'] = ElasticNet()
models['NB'] = GaussianNB()
#非线性
models['SVR'] = SVR()
models['KNN_R'] = KNeighborsRegressor()
models['CART_R'] = DecisionTreeRegressor()
models['RFR'] = RandomForestRegressor()#随机森林
# 评估算法
results = []
for key in models:
kfold = KFold(n_splits=10, random_state=seed,shuffle=True)
# scoring = ['r2','neg_mean_squared_error','neg_mean_absolute_error'] #回归
cv_results = cross_val_score(models[key], X_train, Y_train, cv=kfold, scoring='r2')
results.append(cv_results)
print('%s: %.3f%% (%.3f%%)' %(key, cv_results.mean()*100, cv_results.std()))
from sklearn.model_selection import cross_val_score
#线性回归
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.linear_model import ElasticNet
#非线性回归
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# 算法审查
models = {}
# ****************************************Regression****************************************
#线性
models['LinearR'] = LinearRegression()
models['ridge'] = Ridge()
models['lasso'] = Lasso()
models['EN'] = ElasticNet()
models['NB'] = GaussianNB()
#非线性
models['SVR'] = SVR()
models['KNN_R'] = KNeighborsRegressor()
models['CART_R'] = DecisionTreeRegressor()
models['RFR'] = RandomForestRegressor()#随机森林
# 评估算法
results = []
for key in models:
kfold = KFold(n_splits=10, random_state=seed,shuffle=True)
# scoring = ['r2','neg_mean_squared_error','neg_mean_absolute_error'] #回归
cv_results = cross_val_score(models[key], X_train, Y_train, cv=kfold, scoring='r2')
results.append(cv_results)
print('%s: %.3f%% (%.3f%%)' %(key, cv_results.mean()*100, cv_results.std()))
评价指标
分类
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score,f1_score,roc_auc_score
#使用评估数据集评估算法
svm = SVC()
svm.fit(X=X_train, y=Y_train)
predictions = svm.predict(X_validation)
print(roc_auc_score(Y_validation, predictions))
print(f1_score(Y_validation, predictions,average='micro'))
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))# 混淆矩阵
print(classification_report(Y_validation, predictions))# 分类报告
"""
# 二分类混淆矩阵
tn, fp, fn, tp = confusion_matrix(y_test, predictions).ravel()
print(pd.DataFrame(confusion_matrix(y_test, predictions),
columns=['Predicted False', "Predicted True"], index=['Actual False', 'Actual True']))
"""
#使用评估数据集评估算法
svm = SVC()
svm.fit(X=X_train, y=Y_train)
predictions = svm.predict(X_validation)
print(roc_auc_score(Y_validation, predictions))
print(f1_score(Y_validation, predictions,average='micro'))
print(accuracy_score(Y_validation, predictions))
print(confusion_matrix(Y_validation, predictions))# 混淆矩阵
print(classification_report(Y_validation, predictions))# 分类报告
"""
# 二分类混淆矩阵
tn, fp, fn, tp = confusion_matrix(y_test, predictions).ravel()
print(pd.DataFrame(confusion_matrix(y_test, predictions),
columns=['Predicted False', "Predicted True"], index=['Actual False', 'Actual True']))
"""
回归
from sklearn.metrics import mean_absolute_error,mean_squared_error,r2_score
#使用评估数据集评估算法
svm = SVR()
svm.fit(X=X_train, y=Y_train)
predictions = svm.predict(X_validation)
print(mean_absolute_error(Y_validation, predictions))
print(mean_squared_error(Y_validation, predictions))
print(r2_score(Y_validation, predictions))
#使用评估数据集评估算法
svm = SVR()
svm.fit(X=X_train, y=Y_train)
predictions = svm.predict(X_validation)
print(mean_absolute_error(Y_validation, predictions))
print(mean_squared_error(Y_validation, predictions))
print(r2_score(Y_validation, predictions))
Visualization
中文支持
plt.rcParams['font.family'] = ['Arial Unicode MS'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
sns.set_style('ticks', {'font.sans-serif': ['Arial Unicode MS', 'Arial']}) #用来解决中文方块化的问题
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
sns.set_style('ticks', {'font.sans-serif': ['Arial Unicode MS', 'Arial']}) #用来解决中文方块化的问题
Chart Decision Tree
pd.plotting
pd.plotting.scatter_matrix(df, c=y_train, figsize=(15,15), marker=‘0’, hist_kwds={‘bins’:50},s=60,alpha=.8, cmap=mglearn.cm3)
对角线部分: 核密度估计图(Kernel Density Estimation),就是用来看某 一个 变量分布情况,横轴对应着该变量的值,纵轴对应着该变量的密度(可以理解为出现频次)。
非对角线部分:两个 变量之间分布的关联散点图。将任意两个变量进行配对,以其中一个为横坐标,另一个为纵坐标,将所有的数据点绘制在图上,用来衡量两个变量的关联度(Correlation)
对角线部分: 核密度估计图(Kernel Density Estimation),就是用来看某 一个 变量分布情况,横轴对应着该变量的值,纵轴对应着该变量的密度(可以理解为出现频次)。
非对角线部分:两个 变量之间分布的关联散点图。将任意两个变量进行配对,以其中一个为横坐标,另一个为纵坐标,将所有的数据点绘制在图上,用来衡量两个变量的关联度(Correlation)
matplotlib
>>> import matplotlib.pyplot as plt
>>> import matplotlib.pyplot as plt
Create Plot
#Figure
>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))
>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))
#Axes
>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) # row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)
>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) # row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)
Plotting Routines
1D Data
>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y-values and 0
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y-values and 0
Vector Fields
>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows
Data Distributions
>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows
2D Data or Images
>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img,
cmap='gist_earth',
interpolation='nearest',
vmin=-2,
vmax=2)
#Colormapped or RGB arrays
>>> im = ax.imshow(img,
cmap='gist_earth',
interpolation='nearest',
vmin=-2,
vmax=2)
#Colormapped or RGB arrays
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour
Colors, Color Bars & Color Maps
>>> plt.plot(x, x, x, x**2, x, x**3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c='k')
>>> fig.colorbar(im, orientation='horizontal')
>>> im = ax.imshow(img,cmap='seismic')
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c='k')
>>> fig.colorbar(im, orientation='horizontal')
>>> im = ax.imshow(img,cmap='seismic')
Markers
>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker=".")
>>> ax.plot(x,y,marker="o")
>>> ax.scatter(x,y,marker=".")
>>> ax.plot(x,y,marker="o")
Linestyles
>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls='solid')
>>> plt.plot(x,y,ls='--')
>>> plt.plot(x,y,'--',x**2,y**2,'-.')
>>> plt.setp(lines,color='r',linewidth=4.0)
>>> plt.plot(x,y,ls='solid')
>>> plt.plot(x,y,ls='--')
>>> plt.plot(x,y,'--',x**2,y**2,'-.')
>>> plt.setp(lines,color='r',linewidth=4.0)
Text & Annotations
>>> ax.text(1,-2.1,'Example Graph',style='italic')
>>> ax.annotate("Sine",xy=(8, 0),xycoords='data',xytext=(10.5, 0),textcoords='data',arrowprops=dict(arrowstyle="->",connectionstyle="arc3"),)
>>> ax.annotate("Sine",xy=(8, 0),xycoords='data',xytext=(10.5, 0),textcoords='data',arrowprops=dict(arrowstyle="->",connectionstyle="arc3"),)
Limits, Legends & Layouts
Limits & Autoscaling
>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal') #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5)# Set limits for x-axis
Legends
>>> ax.set(title='An Example Axes', ylabel='Y-Axis',xlabel='X-Axis')#Set a title and x-and y-axis labels
>>> ax.legend(loc='best') #No overlapping plot elements
Ticks
>>> ax.xaxis.set(ticks=range(1,5), ticklabels=[3,100,-12,"foo"])#Manually set x-ticks
>>> ax.tick_params(axis='y', direction='inout',length=10)#Make y-ticks longer and go in and out
Subplot Spacing
>>> fig3.subplots_adjust(wspace=0.5, hspace=0.3,left=0.125,right=0.9,top=0.9,bottom=0.1)#Adjust the spacing between subplots
>>> fig.tight_layout() #Fit subplot(s) in to the figure area
Axis Spines
>>> ax1.spines['top'].set_visible(False)# Make the top axis line for a plot invisible
>>> ax1.spines['bottom'].set_position(('outward',10))
>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal') #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5)# Set limits for x-axis
Legends
>>> ax.set(title='An Example Axes', ylabel='Y-Axis',xlabel='X-Axis')#Set a title and x-and y-axis labels
>>> ax.legend(loc='best') #No overlapping plot elements
Ticks
>>> ax.xaxis.set(ticks=range(1,5), ticklabels=[3,100,-12,"foo"])#Manually set x-ticks
>>> ax.tick_params(axis='y', direction='inout',length=10)#Make y-ticks longer and go in and out
Subplot Spacing
>>> fig3.subplots_adjust(wspace=0.5, hspace=0.3,left=0.125,right=0.9,top=0.9,bottom=0.1)#Adjust the spacing between subplots
>>> fig.tight_layout() #Fit subplot(s) in to the figure area
Axis Spines
>>> ax1.spines['top'].set_visible(False)# Make the top axis line for a plot invisible
>>> ax1.spines['bottom'].set_position(('outward',10))
Save Plot
Save figures
>>> plt.savefig('foo.png')
Save transparent figures
>>> plt.savefig('foo.png', transparent=True)
>>> plt.savefig('foo.png')
Save transparent figures
>>> plt.savefig('foo.png', transparent=True)
seaborn
>>> import seaborn as sns
>>> import matplotlib.pyplot as plt
>>> import seaborn as sns
>>> import matplotlib.pyplot as plt
create a plot
>>> f, ax = plt.subplots(figsize=(5,6)) #Create a figure and one subplot
Seaborn styles
>>> sns.set() #(Re)set the seaborn default
>>> sns.set_style("whitegrid") Set the matplotlib parameters
>>> sns.set_style("ticks", {"xtick.major.size":8,"ytick.major.size":8})
#Set the matplotlib parameters
>>> sns.axes_style("whitegrid")
#Return a dict of params or use with with to temporarily set the style
>>> sns.set_style("whitegrid") Set the matplotlib parameters
>>> sns.set_style("ticks", {"xtick.major.size":8,"ytick.major.size":8})
#Set the matplotlib parameters
>>> sns.axes_style("whitegrid")
#Return a dict of params or use with with to temporarily set the style
Context Functions
>>> sns.set_context("talk") #Set context to "talk"
>>> sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth":2.5})
#Set context to "notebook",Scale font elements and override param mapping
>>> sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth":2.5})
#Set context to "notebook",Scale font elements and override param mapping
Color Palette
>>> sns.set_palette("husl",3) #Define the color palette
>>> sns.color_palette("husl") #Use with with to temporarily set palette
>>> flatui = ["#9b59b6","#3498db","#95a5a6","#e74c3c","#34495e","#2ecc71"]
>>> sns.set_palette(flatui) #Set your own color palette
>>> sns.color_palette("husl") #Use with with to temporarily set palette
>>> flatui = ["#9b59b6","#3498db","#95a5a6","#e74c3c","#34495e","#2ecc71"]
>>> sns.set_palette(flatui) #Set your own color palette
Axisgrid Objects
>>> g.despine(left=True) #Remove left spine
>>> g.set_ylabels("Survived") #Set the labels of the y-axis
>>> g.set_xticklabels(rotation=45) #Set the tick labels for x
>>> g.set_axis_labels("Survived", "Sex")#Set the axis labels
>>> h.set(xlim=(0,5), ylim=(0,5), xticks=[0,2.5,5],yticks=[0,2.5,5])
#Set the limit and ticks of the x-and y-axis
>>> g.set_ylabels("Survived") #Set the labels of the y-axis
>>> g.set_xticklabels(rotation=45) #Set the tick labels for x
>>> g.set_axis_labels("Survived", "Sex")#Set the axis labels
>>> h.set(xlim=(0,5), ylim=(0,5), xticks=[0,2.5,5],yticks=[0,2.5,5])
#Set the limit and ticks of the x-and y-axis
Plot
>>> plt.title("A Title") #Add plot title
>>> plt.ylabel("Survived") #Adjust the label of the y-axis
>>> plt.xlabel("Sex")# Adjust the label of the x-axis
>>> plt.ylim(0,100) #Adjust the limits of the y-axis
>>> plt.xlim(0,10) #Adjust the limits of the x-axis
>>> plt.setp(ax,yticks=[0,5]) #Adjust a plot property
>>> plt.tight_layout() #Adjust subplot params
>>> plt.ylabel("Survived") #Adjust the label of the y-axis
>>> plt.xlabel("Sex")# Adjust the label of the x-axis
>>> plt.ylim(0,100) #Adjust the limits of the y-axis
>>> plt.xlim(0,10) #Adjust the limits of the x-axis
>>> plt.setp(ax,yticks=[0,5]) #Adjust a plot property
>>> plt.tight_layout() #Adjust subplot params
Bokeh
>>> from bokeh.plotting import figure
>>> from bokeh.io import output_file, show
>>> from bokeh.plotting import figure
>>> from bokeh.io import output_file, show
Plotting
>>> from bokeh.plotting import figure
>>> p1 = figure(plot_width=300, tools='pan,box_zoom')
>>> p2 = figure(plot_width=300, plot_height=300,x_range=(0, 8), y_range=(0, 8))
>>> p3 = figure()
>>> p1 = figure(plot_width=300, tools='pan,box_zoom')
>>> p2 = figure(plot_width=300, plot_height=300,x_range=(0, 8), y_range=(0, 8))
>>> p3 = figure()
Renderers & Visual Customizations
Glyphs
ChildTopic
Scatter Markers
>>> p1.circle(np.array([1,2,3]), np.array([3,2,1]),
fill_color='white')
>>> p2.square(np.array([1.5,3.5,5.5]), [1,4,3],
color='blue', size=1)
Line Glyphs
>>> p1.line([1,2,3,4], [3,4,5,6], line_width=2)
>>> p2.multi_line(pd.DataFrame([[1,2,3],[5,6,7]]),
pd.DataFrame([[3,4,5],[3,2,1]]),
color="blue")
Customized Glyphs
Selection and Non-Selection Glyphs
>>> p = figure(tools='box_select')
>>> p.circle('mpg', 'cyl', source=cds_df,
selection_color='red',
nonselection_alpha=0.1)
Hover Glyphs
>>> from bokeh.models import HoverTool
>>> hover = HoverTool(tooltips=None, mode='vline')
>>> p3.add_tools(hover)
Colormapping
>>> from bokeh.models import CategoricalColorMapper
>>> color_mapper = CategoricalColorMapper(
factors=['US', 'Asia', 'Europe'],
palette=['blue', 'red', 'green'])
>>> p3.circle('mpg', 'cyl', source=cds_df,
color=dict(field='origin',
transform=color_mapper),
legend='Origin')
>>> p = figure(tools='box_select')
>>> p.circle('mpg', 'cyl', source=cds_df,
selection_color='red',
nonselection_alpha=0.1)
Hover Glyphs
>>> from bokeh.models import HoverTool
>>> hover = HoverTool(tooltips=None, mode='vline')
>>> p3.add_tools(hover)
Colormapping
>>> from bokeh.models import CategoricalColorMapper
>>> color_mapper = CategoricalColorMapper(
factors=['US', 'Asia', 'Europe'],
palette=['blue', 'red', 'green'])
>>> p3.circle('mpg', 'cyl', source=cds_df,
color=dict(field='origin',
transform=color_mapper),
legend='Origin')
Legend Location
Inside Plot Area
>>> p.legend.location = 'bottom_left'
Outside Plot Area
>>> from bokeh.models import Legend
>>> r1 = p2.asterisk(np.array([1,2,3]), np.array([3,2,1])
>>> r2 = p2.line([1,2,3,4], [3,4,5,6])
>>> legend = Legend(items=[("One" ,[p1, r1]),("Two",[r2])],
location=(0, -30))
>>> p.add_layout(legend, 'right')
>>> p.legend.location = 'bottom_left'
Outside Plot Area
>>> from bokeh.models import Legend
>>> r1 = p2.asterisk(np.array([1,2,3]), np.array([3,2,1])
>>> r2 = p2.line([1,2,3,4], [3,4,5,6])
>>> legend = Legend(items=[("One" ,[p1, r1]),("Two",[r2])],
location=(0, -30))
>>> p.add_layout(legend, 'right')
Legend Orientation
>>> p.legend.orientation = "horizontal"
>>> p.legend.orientation = "vertical"
>>> p.legend.orientation = "vertical"
Legend Background & Border
>>> p.legend.border_line_color = "navy"
>>> p.legend.background_fill_color = "white"
>>> p.legend.background_fill_color = "white"
Rows & Columns Layout
Rows
>>> from bokeh.layouts import row
>>> layout = row(p1,p2,p3)
Columns
>>> from bokeh.layouts import columns
>>> layout = column(p1,p2,p3)
Nesting Rows & Columns
>>>layout = row(column(p1,p2), p3)
>>> from bokeh.layouts import row
>>> layout = row(p1,p2,p3)
Columns
>>> from bokeh.layouts import columns
>>> layout = column(p1,p2,p3)
Nesting Rows & Columns
>>>layout = row(column(p1,p2), p3)
Grid Layout
>>> from bokeh.layouts import gridplot
>>> row1 = [p1,p2]
>>> row2 = [p3]
>>> layout = gridplot([[p1,p2],[p3]])
>>> row1 = [p1,p2]
>>> row2 = [p3]
>>> layout = gridplot([[p1,p2],[p3]])
Tabbed Layout
>>> from bokeh.models.widgets import Panel, Tabs
>>> tab1 = Panel(child=p1, title="tab1")
>>> tab2 = Panel(child=p2, title="tab2")
>>> layout = Tabs(tabs=[tab1, tab2])
>>> tab1 = Panel(child=p1, title="tab1")
>>> tab2 = Panel(child=p2, title="tab2")
>>> layout = Tabs(tabs=[tab1, tab2])
Linked Plots
Linked Axes
>>> p2.x_range = p1.x_range
>>> p2.y_range = p1.y_range
Linked Brushing
>>> p4 = figure(plot_width = 100,
tools='box_select,lasso_select')
>>> p4.circle('mpg', 'cyl', source=cds_df)
>>> p5 = figure(plot_width = 200,
tools='box_select,lasso_select')
>>> p5.circle('mpg', 'hp', source=cds_df)
>>> layout = row(p4,p5)
>>> p2.x_range = p1.x_range
>>> p2.y_range = p1.y_range
Linked Brushing
>>> p4 = figure(plot_width = 100,
tools='box_select,lasso_select')
>>> p4.circle('mpg', 'cyl', source=cds_df)
>>> p5 = figure(plot_width = 200,
tools='box_select,lasso_select')
>>> p5.circle('mpg', 'hp', source=cds_df)
>>> layout = row(p4,p5)
Output & Export
Notebook
>>> from bokeh.io import output_notebook, show
>>> output_notebook()
>>> output_notebook()
HTML
Standalone HTML
>>> from bokeh.embed import file_html
>>> from bokeh.resources import CDN
>>> html = file_html(p, CDN, "my_plot")
>>> from bokeh.embed import file_html
>>> from bokeh.resources import CDN
>>> html = file_html(p, CDN, "my_plot")
>>> from bokeh.io import output_file, show
>>> output_file('my_bar_chart.html', mode='cdn')
>>> output_file('my_bar_chart.html', mode='cdn')
Components
>>> from bokeh.embed import components
>>> script, div = components(p)
>>> from bokeh.embed import components
>>> script, div = components(p)
PNG
>>> from bokeh.io import export_png
>>> export_png(p, filename="plot.png")
>>> export_png(p, filename="plot.png")
SVG
>>> from bokeh.io import export_svgs
>>> p.output_backend = "svg"
>>> export_svgs(p, filename="plot.svg")
>>> p.output_backend = "svg"
>>> export_svgs(p, filename="plot.svg")
Show or Save Your Plots
>>> show(p1)
>>> show(layout)
>>> show(layout)
pyecharts
python
phase1
Introduction to python
basic containers
list,dic,tuple,set,string,int
Packages and modules
numpy,pandas,matplotlib
Functions
Class
Error handling
....
SQL
SQL Server,Oracle,mysql
phase2
statistics
Machine Learning
Scikit Learn,Keras,statsmodel
phase3
Web Development
Django,Tornado,html
0 条评论
下一页