Python3科学计算常见库入门
Numpy快速数据处理库
参见我的博客
http://www.cnblogs.com/brightyuxl/p/8981294.html
http://www.cnblogs.com/brightyuxl/p/8977075.html
http://www.cnblogs.com/brightyuxl/p/8855948.html
http://www.cnblogs.com/brightyuxl/p/8846701.html
SciPy数值计算库
常数和特殊函数
from scipy import constants
print('真空中的光速:{}'.format(constants.c))
print('普朗克常数: {}'.format(constants.h))
print('电子质量(数值,单位,误差): {}'.format(constants.physical_constants['electron mass']))
真空中的光速:299792458.0
普朗克常数: 6.62607004e-34
电子质量(数值,单位,误差): (9.10938356e-31, 'kg', 1.1e-38)
特殊函数
Gamma函数(Gamma)是统计学中经常出现的一个特殊函数:
[Gamma(z) = int_0^{infty}t^{z-1}e^{-t}dt
]
import scipy.special
print(scipy.special.gamma(0))
print(scipy.special.gamma(0.5))
print(scipy.special.gamma(1))
print(scipy.special.gamma(1.5))
print(scipy.special.gamma(2))
inf
1.7724538509055159
1.0
0.8862269254527579
1.0
(ln(|Gamma(x)|))可以计算更大的数
scipy.special.gammaln(1000)
5905.220423209181
import numpy as np
print(1+1e-20)
print(np.log(1+1e-20))
print(scipy.special.log1p(1e-20)) # log1p(x) = log(1+x)
1.0
0.0
1e-20
matplotlib快速绘图库
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2)
plt.figure(figsize=(8,4))
plt.plot(x,y,label='$sin(x)$', color='red',linewidth=2)
plt.plot(x,z,'b--',label='$cos(x^2)$')
plt.xlabel('Time(s)')
plt.ylabel('Volt')
plt.title('PyPlot First Example')
plt.ylim(-1.2,1.2)
plt.legend
plt.savefig('My_figure')
plt.show()
Pandas数据分析友好库
import pandas as pd
s = pd.Series([1,2,3,4,5,6], index=['a','b','c','d','e','f'])
print(s)
a 1
b 2
c 3
d 4
e 5
f 6
dtype: int64
SymPy符号运算库
[e^{ipi} + 1 = 0
]
from sympy import E, I, pi
E**(I*pi) + 1 # 证明欧拉等式
0
from sympy import symbols, expand
x = symbols('x')
expand(E**(I*x))
exp(I*x)
Python3小知识点
1.写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
其实人跟树一样,越是向往高处的阳光,它的根就越要伸向黑暗的地底。
def StringCounter(seq):
dic = {
'num':0,
'string':0,
'space':0,
'other':0
}
for s in seq:
if s.isdigit():
dic['num'] += 1
elif s.isalpha():
dic['string'] += 1
elif s.isspace():
dic['space'] += 1
else:
dic['other'] += 1
return dic
# 验证函数
print(StringCounter('dfasfdaslfkjl 12312 @@!#!@#'))
{'num': 5, 'string': 13, 'space': 5, 'other': 7}
2.分析下列代码的运行过程
x=1
def f1():
def f2():
print(x)
return f2
x=100
def f3(func):
x=2
func()
x=10000
f3(f1())
10000
3.查看a与b的不同之处
a = [1,2,3]
b = [(1),(2),(3)]
print(a == b)
print(a is b)
True
False
4.切片回忆
name = ['trek', 'cannondale', 'redline', 'specialized', 'trek']
print('1:', name)
print('2:', name[0], name[2])
print('3:', name[1:3]) #切片
print('4:', name[-2:]) #切片
print('5:', name[::-1]) #切片的结果是倒序排列
print('6:', name[:-1]) #切片的结果是,输出到倒数第二位 -1-1=-2
1: ['trek', 'cannondale', 'redline', 'specialized', 'trek']
2: trek redline
3: ['cannondale', 'redline']
4: ['specialized', 'trek']
5: ['trek', 'specialized', 'redline', 'cannondale', 'trek']
6: ['trek', 'cannondale', 'redline', 'specialized']