#in[1]
#常规输入
a=[1,2,3]
b=[]
for i in a:
b.append(i+2)
print (b)
#out[1]
[3, 4, 5]
#in[2]
#列表解析
a=[1,2,3]
b=[]
b=[i+2 for i in a]
print (b)
#out[2]
[3, 4, 5]
python引入了自编这一方便的概念。从数学上讲它实际上是一个映射。通俗来讲,它相当于一个列表,然而它的“下标”不再是以0开头的数字,而是让自己定义的“键”(Key)开始!
python内置了集合这一数据结构,同数学上的集合概念基本一致,它与列表的区别在于1.它的元素是不重复的,而且是无序的。
2.它不支持索引。一般我们通过花括号{},或者set()函数来创建一个集合。
#创建举例
s={1,2,2,3} #注意2会自动去重,得到{1,2,3}
s=set(1,2,2,3) #同样,它将列表转换为集合,得到{1,2,3}
# in[3]
# 特殊运算
t = {1,2,3,4,5,6,7}
s = {10,9,8,7,6,5,4}
a = t | s # t和s的并集
b = t & s # t和s的交集
c = t - s # t和s的差集
d = t ^ s # t和s的对称差(项在t或s中,但不会同时出现在t,s中)
print(a)
print(b)
print(c)
print(d)
#out[3]
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{4, 5, 6, 7}
{1, 2, 3}
{1, 2, 3, 8, 9, 10}
函数式编程(Functional Programming)或者函数程序设计,又称泛函编程,是一种编程范型,它将计算机运算视为数学上的函数计算,并且避免使用程序状态以及易变对象。简单来讲,函数式编程是一种“广播式”的编程,一般结合lambda定义函数,用于科学计算中,会显得特别简洁方便。
# in[4]
# map()函数运用举例
a = [1, 2, 3]
# 首先用列表解析实现上述过程
b = [i + 2 for i in a]
print(b)
# 而利用map()函数
c = map(lambda x: x + 2, a)
c = list(c)
print(c)
# out[4]
[3, 4, 5]
[3, 4, 5]
s = 1
for i in range(1, n + 1):
s = s * i
# in[5]
b = filter(lambda x: x > 5 and x < 8, range(1, 10))
b = list(b)
print(b)
# out[5]
[6, 7]
以上所有的函数都可以用for,while 循环语句进行替换,使用的以上函数的目的是兼顾简洁和效率。
import math
math.sin(1) # 计算正弦
math.cos(1) # 计算余弦
math.pi #内置的圆周率常数
导入库的方法除了使用“import 库名 ”,之外还可以为库名取一个别名:
import math as m
m.sin(1) # 计算正弦
此外如果并不需要导入库的所有函数,可以特别指定导入函数的名字:
from math import exp as e #只导入math库中的exp函数,并起别名为e
e(1) #计算指数
sin(1) # 此时sin(1)和math.sin(1)都会出错,因为没被导入
# in[6]
import numpy as np
a = np.array([2, 0, 1, 5])
print(a)
print(a[:3])
print(a.min())
a.sort()
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b * b)
# out[6]
[2 0 1 5]
[2 0 1]
0
[[ 1 4 9]
[16 25 36]]
# in[7]
# 求解方程组:2x1-x2^2=1,x1^2-x2=2
from scipy import integrate
from scipy.optimize import fsolve
def f(x):
x1 = x[0]
x2 = x[1]
return [2 * x1 - x2**2 - 1, x1**2 - x2 - 2]
result = fsolve(f, [1, 1])
print(result)
# 数值积分
def g(x):
return(1 - x**2)**0.5
pi_2, err = integrate.quad(g, -1, 1)
print(pi_2 * 2)
# out[7]
[1.91963957 1.68501606]
3.1415926535897967
# in[8]
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
y = np.sin(x) + 1
z = np.cos(x**2) + 1
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='$\sin x+1$', color='red', linewidth=2)
plt.plot(x, z, 'b--', label=r'$\cos x^2+1$')
plt.xlabel('time(s)')
plt.ylabel('volt')
plt.title('a simple example')
plt.ylim(0, 2.2)
plt.legend()
plt.show()
import pandas as pd
s=pd.Series([1,2,3],index=['a','b','c']) # 创建序列
d=pd.DataFrame([[1,2,3],[4,5,6]], columns = ['a','b','c']) #创建表
d2=pd.DataFrame(s) #用已有序列创建表格
d.head() #预览前面5行数据
d.describe() # 数据基本统计
# 读取文件
pd.read_excel('data.xls') #读取RXCEL文件
pd.read_csv('data.csv',encoding='utf-8')
# ADF平稳性检验的例子
from statsmodels.tsa.stattools import adfuller as ADF # 导入ADF验证
import numpy as np
ADF(np.random.rand(100)) # 返回的结果有ADF值和P值
from sklearn.linear_model import LinearRegression #导入线性回归模型
model = LinearRegression() #建立线性回归模型
print(model)
数据质量分析的主要任务是检查原始数据中是否存在脏数据,脏数据一般是指不符合要求,以及不能直接进行相应分析的数据,在常见的数据挖掘工作中,脏数据包括:缺失值,异常值,不一致值,重复数据及含有特殊符号(如#,¥,*)的数据。
#-*- coding: utf-8 -*-
import pandas as pd
catering_sale = '../data/catering_sale.xls' #餐饮数据
data = pd.read_excel(catering_sale, index_col = u'日期') #读取数据,指定“日期”列为索引列
分布分析能够揭示数据的分布特征和分布类型。
# 数据统计量分析代码
from __future__ import print_function
import pandas as pd
catering_sale = '../data/catering_sale.xls' #餐饮数据
data = pd.read_excel(catering_sale, index_col = u'日期') #读取数据,指定“日期”列为索引列
data = data[(data[u'销量'] > 400)&(data[u'销量'] < 5000)] #过滤异常数据
statistics = data.describe() #保存基本统计量
statistics.loc['range'] = statistics.loc['max']-statistics.loc['min'] #极差
statistics.loc['var'] = statistics.loc['std']/statistics.loc['mean'] #变异系数
statistics.loc['dis'] = statistics.loc['75%']-statistics.loc['25%'] #四分位数间距
print(statistics)
——《python数据分析与挖掘实战》