三天速通复习python
阶段一 了解IDE
使用pycharm :
新建项目:会生成.idea目录; 设置编辑器:下载Anaconda,设置脚本路径和名称,名称建议与项目名相同; 设置断点:点击小虫按钮,通过步入前进; 中文:右下角为UTF-8 使用jupeyter :
在Anaconda navigator中下载 一种笔记软件,基于浏览器实现,由python编译器和markdown语法构成 其他:
阶段二 基本语法
1. 注释
"""
多行注释
写代码之前可以先写多行注释对接下来的操作进行整体描述
"""
2. 操作符
+ - * / %
//
**
5 / 2
+= -= *= /= %= **= //=
True False
not &——and |——or
< <= > >= != ==
1 < 2 < 3
2 < 3 < 2
'I say:"you are a liar!"'
"Hello " + "world!"
"This is a string" [0 ]
"%s can be %s" % ("strings" , "interpolated" )
"{0} can be {1}" .format ("strings" , "formatted" )
"{name} wants to eat {food}" .format (name="Bob" , food="lasagna" )
None
"etc" is None
None is None
0 == False
"" == False
3. 变量和集合
print ("I'm Python. Nice to meet you!" )
input (n)
some_var = 5
some_var
a=b=c=1
some_other_var
"yahoo!" if 3 > 2 else 2
li = []
other_li = [4 , 5 , 6 ]
li.append(1 )
li.append(2 )
li.append(4 )
li.append(3 )
li.pop()
li.append(3 )
li[0 ]
li[-1 ]
li[4 ]
li[0 :3 ] = li[:3 ] = li[0 :]
li[-1 :2 ]
del li[2 ]
li + other_li
li.extend(other_li)
1 in li
len (li)
[i for i in range (1 ,100 ) if i%10 ==0 ]
tup = (1 , 2 , 3 )
tup[0 ]
tup[0 ] = 3
len (tup)
tup + (4 , 5 , 6 )
tup[:2 ]
2 in tup
a, b, c = (1 , 2 , 3 )
d, e, f = 4 , 5 , 6
e, d = d, e
empty_dict = {}
filled_dict = {"one" : 1 , "two" : 2 , "three" : 3 }
filled_dict["one" ]
filled_dict.keys()
filled_dict.values()
filled_dict.items()
"one" in filled_dict
1 in filled_dict
filled_dict["four" ]
filled_dict["four" ] = 4
filled_dict.get("one" )
filled_dict.get("four" )
filled_dict.get("one" , 4 )
filled_dict.get("four" , 4 )
filled_dict.setdefault("five" , "nvidia" )
filled_dict.setdefault("five" , 5 )
empty_set = set ()
some_set = set ([1 , 2 , 2 , 3 , 4 ])
filled_set = {1 , 2 , 2 , 3 , 4 }
filled_set.add(5 )
other_set = {3 , 4 , 5 , 6 }
filled_set & other_set
filled_set | other_set
{1 , 2 , 3 , 4 } - {2 , 3 , 5 }
2 in filled_set
10 in filled_set
4. 选择、循环结构
some_var = 5
if some_var > 10 :
print "some_var is totally bigger than 10."
elif some_var < 10 :
print "some_var is smaller than 10."
else :
print "some_var is indeed 10."
for animal in ["dog" , "cat" , "mouse" ]:
print "%s is a mammal" % animal
for i in range (4 ):
print i
x = 0
while x < 4 :
print x
x += 1
5. 函数
def add (x, y ):
print "x is %s and y is %s" % (x, y)
return x + y
add(5 , 6 )
add(y=6 , x=5 )
def varargs (*args ):
return args
varargs(1 , 2 , 3 )
def keyword_args (**kwargs ):
return kwargs
keyword_args(big="foot" , loch="ness" )
def all_the_args (*args, **kwargs ):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
args = (1 , 2 , 3 , 4 )
kwargs = {"a" : 3 , "b" : 4 }
all_the_args(*args)
all_the_args(**kwargs)
all_the_args(*args, **kwargs)
def create_adder (x ):
"""先传外,再传内"""
def adder (y ):
return x + y
return adder
add_10 = create_adder(10 )
add_10(3 )
(lambda x: x > 2 ) (3 )
map (add_10, [1 , 2 , 3 ])
filter (lambda x: x > 5 , [3 , 4 , 5 , 6 , 7 ])
max () sum () min () abs ()
[add_10(i) for i in [1 , 2 , 3 ]]
[x for x in [3 , 4 , 5 , 6 , 7 ] if x > 5 ]
6. 类
class Human (object ):
species = "H. sapiens"
__species0 =''
def __init__ (self, name ):
self.name = name
def say (self, msg ):
return "%s: %s" % (self.name, msg)
@classmethod
def get_species (cls ):
return cls.species
@staticmethod
def grunt ():
return "*grunt*"
i = Human(name="Ian" )
print i.say("hi" )
j = Human("Joel" )
print j.say("hello" )
i.get_species()
Human.species = "H. neanderthalensis"
i.get_species()
j.get_species()
Human.grunt()
7. 模块
import math
print math.sqrt(16 )
from math import ceil, floor
print ceil(3.7 )
print floor(3.7 )
from math import *
import math as m
math.sqrt(16 ) == m.sqrt(16 )
import math
dir (math)
阶段三 以题带练
题目来源:Data-Science-Notes 题目只是为了保持手感,加上本人最近时间有限,故只做三天;第一天是阶段一之后复习巩固,第二天是学完数据分析三剑客后复习巩固,第三天是复写本人毕业设计中matlab代码后的感想
day 1
输入函数input()
返回的是string
类型,如果是整数,需在前文添加int
,即:n=int(input())
day 2
连续输入a=input().split(',')
,其中数据以逗号分隔开来;还可以与函数map()
联用 类中self
可以不预设属性值,直接用self.n
来传递参数 range()
函数用法:
range (stop)
range (start, stop[, step])
str .join(sequence)
',' .join([1 ,2 ,3 ])
二维数组正确的创建方法:li2=[[0 for j in range(n)]for i in range(m)]
list
中排序函数的用法:list.sort( key=None, reverse=False)
内建函数sorted()
的用法:sorted(iterable, key=None, reverse=False)
day 3
list .count(obj)
str .count(sub, start= 0 ,end=len (string))
list .remove(obj)
bin (obj)
oct (obj)
hex (obj)
int (obj,n)
ord()
函数:返回对应ASCII码的十进制整数 -> ord(c)
\n
是换行符要多用[]
,只有函数才用()
阶段四 数据分析
1. numpy
介绍:数值计算拓展,全称为numeric python;通常以import numpy as np
调用 基本用法:
arr=np.array([1 ,2 ])
arr+1
arr1 + arr2
arr=np.zeros(n)
arr=np.ones(n [,dtype='type name' ])
arr.fill(n)
arr.astype('type name' )
arr=np.arange(start,stop [,step])
arr=np.linspace(start,stop,num)
arr=np.random.rand(num)
arr=np.random.randn(num)
arr=np.random.randint(start,stop,num)
arr.dtype
arr.shape
arr.size
arr.ndim
arr[::2 ]
arr2=arr[1 :]-arr[:-1 ]
where(condition)
arr=np.array([[0 ,1 ,2 ,3 ],[10 ,11 ,12 ,13 ]])
arr.shape
arr[1 ,3 ]
arr[1 ,3 ]=-1
arr[1 ]
arr[:,1 ]
arr3=arr[2 :4 ].copy()
index=[1 ,2 ,-3 ]
arr3=arr[index]
mask=np.array([0 ,1 ,2 ,……],dtype='bool' )
arr3=arr[mask]
进阶学习:
arr=np.array([],dtype=float )
arr=np.asarray(arr.dtype=float )
arr2=arr.astype('float' )
np.sort(arr)
np.argsort(arr)
np.sum (arr) or arr.sum ()
np.max (arr) or arr.max ()
np.min (arr) or arr.min ()
np.mean(arr) or arr.mean()
np.std(arr) or arr.std()
np.cov(arr) or arr.cov()
arr.shape=row,colume
arr2=arr.reshape(2 ,3 )
arr.T
arr2=arr.transpose()
np.concatenate((x,y),axis=1 or 0 )
np.stack() or np.vstack()
要学会查文档,numpy+python约等于matlab了
2. pandas
基本介绍:解决数据分析任务创建的,全称为python data analysis,通常以import pandas as pd
调用 基本数据结构:
一维数组:Series,通常以pd.Series()
调用,下标默认为数字
s=pd.Series([num],index=[])
s.index
s.values
s.index.name='索引'
s.index=list ("abcdef" )
二维数组:DataFrame,表格型数据结构,是一个以series的容器,重中之重
data=pd.date_range('20180101' ,periods=6 )
df=pd.DataFrame(np.random.randn(6 ,4 ),index=date,colums=list ('ABCD' ))
or
df2=pd.DataFrame({'A' :1 ,'B' :……})
文件读写
df=pd.read_excel(r'filepath' )
df.to_excel(r'filepath' )
增删改查
df.head()
df.tail()
df.index()
df.values()
df.colume()
df.iloc[index]
df.loc[index]
dit=['name' :'the Avenger' ,'A' :12 ,……]
s=pd.Series(dit)
df=df.append(s)
df=df.drop([index],axis=0 )
df.columns
df['name' ][:5 ]
df['name' ]['A' ]
df['sex' ]=range (1 ,len (df)+1 )
df=df.drop(['sex' ],axis=1 )
df.index=range (len (df))
df.loc[[index],[column]]
df['name' ]=='Linxson'
df[df['name' ]=='Linxson' ][:5 ]
df[(df.name=='Linxson' )&(df.sex=male)][:5 ]
缺失值及异常值处理方法
df['column' ].isnull()
df['name' ].fillna(0 ,inpace=True )
df.dropna(how='all' ,inplace=True ,axis=0 )
数据格式转换
df['name' ].dtype
df['name' ]=df['name' ].astype('int' )
排序
df.sort_values(by='name' ,ascending=False )
df.sort_values(by=['name' ,'sex' ],ascending=False )
基本统计分析
df.describe()
df['name' ].min ()
df['name' ].max ()
df['name' ].mean()
df['name' ].median()
df['name' ].var()
df['name' ].std()
df['name' ].sum ()
df['name' ,'sex' ].cov()
df['name' ].unique()
df['name' ].value_counts()
df['name' ].replace('Linxson' ,'NUX' ,impalce=True )
数据透视 pivot_talbe
pd.pivot_table(df,index=['name' ])
pd.pivot_table(df,index=['name' ,'sex' ])
pd.set_option('max_columns' ,500 )
pd.set_option('max_rows' ,500 )
pd.pivot_table(df,index=['name' ],values=['sex' ])
pd.pivot_table(df,index=['name' ],values=['sex' ],aggfunc=np.mean)
pd.pivot_table(df,index=['name' ],values=['sex' ],aggfunc=np.mean,fill_value=0 )
pd.pivot_table(df,index=['name' ],values=['sex' ],aggfunc=np.mean,fill_value=0 ,margins=True )
数据重塑和轴向旋转
层次化索引:类似于合并同类项,本质是一级目录、二级目录–看图好理解
s=pd.Series(np.arange(1 ,4 ),index=[['a' ,'a' ,'b' ],['c' ,'d' ,'d' ]])
"""
a c 1
d 2
b d 3
"""
Dataframe的层次化索引:s.unstack()
将Series转换为Dataframe
data=pd.Dataframe(np.arange(12 ).reshape(1 ,3 ),index=[['a' ,'a' ,'b' ,'b' ],[1 ,2 ,1 ,2 ]],columns=[['A' ,'A' ,'B' ],['z' ,'x' ]])
data.columns.names=['column1' ,'column2' ]
data.swaplevel('column1' ,'column2' )
df=df.reset_index()
data.T
数据分组与分组运算: GroupBy
group1=df.groupby(df['name' ])
group2=df.groupby(df['name' ,'sex' ])
离散化处理:区间化、分组化
pd.cut(x,bins,right=True ,labels=None ,retbins=False ,precision=3 ,include_lowest=False )
合并数据集
append:先把数据集拆分为多个,然后再上下拼接 merge:连接两个对象
pd.merge(left, right, how = 'inner' , on = None , left_on = None , right_on = None ,
left_index = False , right_index = False , sort = True ,
suffixes = ('_x' , '_y' ), copy = True , indicator = False , validate=None )
concat:将多个数据集进行批量合并 pd.concat([df1,df2,df3])
3. matplotlib
基本介绍:包含一系列类似于matlab中绘图函数的相关函数
导入库调用:import matplotlib.pyplot as plt
jupyter中,使用魔术命令:% matplotlib inline
基本用法
plt.show()
plt.plot(x,y)
plt.plot([1 ,2 ,3 ,4 ])
plt.ylabel('y' ,fontsize=14 )
plt.xlabel('x' )
plt.axis(xmin,xmax,ymin,ymax)
t=np.arange(0. ,5. ,0.2 )
plt.plot(t,t,'r--' ,t,t**2 ,'bs' ,t,t**3 ,'g^' )
plt.plot(x,y,linewidth=1.0 ,color='r' )
line1=plt.plot(x,y,'r-' )
line1.linewidth=1.0
plt.setp(line1,'linewidth' =1.0 )
plt.figure(num)
plt.subplot(numrows,numcols,fignum)
def f (t ):
return np.exp(-t)*np.cos(2 *np.pi*t)
plot(x,f(x))
实例操作
import warnings
warnings.filterwarning('ignore' )
plt.rcParms['font.sans-serif' ]=['SimHei' ]
plt.rcParms['axes.unicode_minus' ]=False
plt.xticks(rotation=90 )
for a,b in zip (x,y):
plt.text(a,b+10 ,b,ha='center' ,va='bottom' ,fontsize=10 )
annottate(xy,xylabel)
plt.bar(x,y,'g' )
plt.pie(x,explode,label,……)
plt.hist(arr,bins,……)
ax1=……
mlab.normpdf(bins,df,'name' .mean(),df['name' ].std())
ax2=ax1.twinx()
ax2.plot()
plt.scatter()
plt.boxplot()
ax = sns.heatmap()
4. 数据分析报告
背景介绍:说明问题,阐述问题重要性 数据来源与说明:公开渠道、说明样本含义、制作图表 描述性分析:分维度可视化展示,描述图表 统计建模:解决问题 结论建议
阶段五 WNTR包
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程