[Python] 01 - Number and Matrix

故事背景


一、大纲

如下,chapter4 是个概览,之后才是具体讲解。

 

二、 编译过程

Ref: http://www.dsf.unica.it/~fiore/LearningPython.pdf


 

 



 

 

 

 

 

 

三、 四个概念

145/1594

Python programs can be decomposed into modules, statements, expressions, and objects, as follows:

1. Programs are composed of modules.

2. Modules contain statements.

3. Statements contain expressions.

4. Expressions create and process objects.

 

四、变量类型

Python’s Core Data Types


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

五、枚举类

From: 使用枚举类

使用默认值

from enum import Enum
# 定义 Month
= Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
# 遍历
for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)

 

自定义值

@unique装饰器可以帮助我们检查保证没有重复值,这里使用了“类”。

from enum import Enum, unique

@unique
class Weekday(Enum):
    Sun = 0 # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6

 

六、举些栗子

  1 # coding: utf-8
  2 
  3 # <h1 align="center">Built-ins</h1>
  4 
  5 # ## Types and classes
  6 
  7 # In[1]:
  8 
  9 
 10 type(True), type(1), type (1.), type('1'), type([]), type(()), type({}), type({1})
 11 
 12 
 13 # In[2]:
 14 
 15 
 16 x = 1.
 17 type(x)
 18 
 19 
 20 # In[3]:
 21 
 22 
 23 type(bool), type(int), type(float), type(str), type(list), type(type)
 24 
 25 
 26 # In[4]:
 27 
 28 
 29 isinstance(1, int), isinstance(1, float), isinstance({2}, set), isinstance({}, set)
 30 
 31 
 32 # In[5]:
 33 
 34 
 35 issubclass(bool, int), issubclass(int, float)
 36 
 37 
 38 # ## Literal representations
 39 
 40 # In[6]:
 41 
 42 
 43 bool(True), bool(-17.8), bool('17'), bool([]), bool({}), bool(None), bool('')
 44 
 45 
 46 # In[7]:
 47 
 48 
 49 int('17'), int('10001', 2), int('21', 8), int('15', 12), int('11', 16), int('h', 22)
 50 
 51 
 52 # In[8]:
 53 
 54 
 55 int(True), int(17), int(-17), int(0b10001), int(0o21), int(0x11), int(17.8)
 56 
 57 
 58 # In[9]:
 59 
 60 
 61 bin(True), bin(17), bin(-17), bin(0b10001), bin(0o21), bin(0x11)
 62 
 63 
 64 # In[10]:
 65 
 66 
 67 oct(True), oct(17), oct(-17), oct(0b10001), oct(0o21), oct(0x11)
 68 
 69 
 70 # In[11]:
 71 
 72 
 73 hex(True), hex(17), hex(-17), hex(0b10001), hex(0o21), hex(0x11)
 74 
 75 
 76 # In[12]:
 77 
 78 
 79 float(False), float(17), float(17.), float(17e-1), float(0.17E2), float('170E-1') 
 80 
 81 
 82 # In[13]:
 83 
 84 
 85 print(complex(0), complex(1.5), complex(4.5, -7.5))
 86 print(complex(0).conjugate(), complex(1.5).conjugate(), complex(4.5, -7.5).conjugate())
 87 print(complex(0).real, complex(1.5).real, complex(4.5, -7.5).real)
 88 print(complex(0).imag, complex(1.5).imag, complex(4.5, -7.5).imag)
 89 
 90 
 91 # ## Operations on numbers
 92 
 93 # In[14]:
 94 
 95 
 96 abs(-3.8), abs(-2), abs(3.8)
 97 
 98 
 99 # In[15]:
100 
101 
102 print(round(-3.6), round(-3.5), round(-3.4), round(3.4), round(3.5), round(3.6))
103 print(round(-3.1235, 3), round(-3.123456, 4), round(3.123456, 4), round(3.1235, 3))
104 
105 
106 # In[16]:
107 
108 
109 divmod(13, 5), divmod(-13., 5), divmod(13., -5.), divmod(-13, -5.), divmod(3.5, 2)
110 
111 
112 # In[17]:
113 
114 
115 print(pow(2, 3), pow(-2., -1), pow(4, -0.5), pow(-1, 0.5), pow(-3.8, 0), pow(1j, 1j))
116 print(pow(-2, 3, 3), pow(-2, 3, 5), pow(2, 3, 3), pow(2, 3, 5))
117 
118 
119 # ## Strings
120 
121 # In[18]:
122 
123 
124 print(ord('c'), ord('\xf7'), ord(''), ord('\u2603'))
125 print(chr(99), chr(247), chr(8226), chr(9731))
126 
127 
128 # In[19]:
129 
130 
131 ascii('Ça me tient ∞ment à cœur\t')
132 
133 
134 # In[20]:
135 
136 
137 repr('A string'), str('A string')
138 
139 
140 # In[21]:
141 
142 
143 a = 2; b = 4.5
144 eval('(a + 3.5) * (b + 5.)')
145 
146 
147 # In[22]:
148 
149 
150 message = input('Input your message: ')
151 print('Your message is:', message)
152 
153 
154 # ## Creating and processing iteratables
155 
156 # In[23]:
157 
158 
159 print(tuple(range(4)), tuple(range(4, 8)), tuple(range(4, 16, 3)))
160 print(tuple(range(-8)), tuple(range(-8, -4)), tuple(range(-16, -8, -3)))
161 print()
162 
163 print(range(2, 8, 2).count(4), range(2, 8, 2).count(5), range(2, 8, 2).index(4))
164 
165 
166 # In[24]:
167 
168 
169 print(list(enumerate({10, 15, 25, 40})))
170 print(dict(enumerate((10, 15, 25, 40), 3)))
171 
172 
173 # In[25]:
174 
175 
176 print(list(zip([1, 2, 3, 4], [11, 12, 13], [21, 22, 23, 24, 25], [31, 32, 33])))
177 print(list(zip(*zip([1, 2, 3, 4], [11, 12, 13], [21, 22, 23, 24, 25], [31, 32, 33]))))
178 
179 
180 # In[26]:
181 
182 
183 print(list(map(sorted,
184                [(1, 2, 3), (7, 5, 4, 6, 8), (10, 9), (11,)])))
185 print(set(map(int.__add__,
186               [1, 2, 3, 4, 5], [11, 12, 13])))
187 print(dict(map(lambda x: (x, 2 * x),
188                (0, 1, 2, 3, 4, 5))))
189 print(tuple(map(lambda x, y, z: len({x, y, z}) == 2,
190                 [1, 20, 30, -4, 5, 60], [-1, 20, 31, 4, 5], [1, 20, 32, 4, -5, 61, 70])))
191 
192 
193 # In[27]:
194 
195 
196 print(list(filter(str.isupper,
197                  {'A': 1, 'b': 2, 'c': 3, 'D': 4, 'E': 5})))
198 print(tuple(filter(lambda x: x < 10,
199                 [-1, 20, -3, -4, 50, 60])))
200 
201 
202 # In[28]:
203 
204 
205 print(sum([3, 1, 7, 5]))
206 print(sum({3: 1, 1: 1, 7: 2, 5: 3}))
207 
208 
209 # In[29]:
210 
211 
212 print(min((3, 1, 7, 5)))
213 # min() accepts also an arbitrary number of arguments
214 print(min(3, 1, 7, 5))
215 
216 
217 # In[30]:
218 
219 
220 print(max({3 : 10, 1: 10, 7: 10, 5: 10}))
221 # max() accepts also an arbitrary number of arguments
222 print(max(3, 1, 7, 5))
223 
224 
225 # In[31]:
226 
227 
228 sorted([2, 1, 3, 4, 0])
229 
230 
231 # In[32]:
232 
233 
234 list(reversed((2, 1, 3, 4, 0)))
235 
236 
237 # In[34]:
238 
239 
240 print(any([0, 0, 0, 0, 0]))
241 print(any((1, 0, 0, 1, 0)))
242 
243 
244 # In[35]:
245 
246 
247 print(all({5, 2, 3, 1, 4}))
248 print(all({5: 1, 2: 1, 3: 1, 0: 1, 4: 4}))
View Code

 

 

 

 

 

让我们开始


一、 表达形式

 

   

二、大数

超长显示 

总之,问题不大。

 

Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux

Type "help", "copyright", "credits" or "license" for more information.

 

>>> len(str(2**1000))

302
length

>>> 2**1000

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
较长

>>> 2**10000 # Are you serious? 

19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
超长

 

 

三、小数

Question:一个比较麻烦的问题,如何解决?

 

print() 函数

数字显示问题,版本变高自动改善,或者通过print作为替代方案。




 

print等价于str,表示:以读者希望的形式表达出来。

In [92]: decimal.Decimal(str(1/3))
Out[92]: Decimal('0.3333333333333333')

In [93]: decimal.Decimal(1/3)
Out[93]: Decimal('0.333333333333333314829616256247390992939472198486328125')

 

decimal 方法

>>> 1 / 3 # Floating-point (add a .0 in Python 2.X)
0.3333333333333333
>>> (2/3) + (1/2)
1.1666666666666665

>>> import decimal # Decimals: fixed precision >>> d = decimal.Decimal('3.141') >>> d + 1 Decimal('4.141')
>>> decimal.getcontext().prec = 2                    // 精度设置 >>> decimal.Decimal('1.00') / decimal.Decimal('3.00')        // 小数计算 Decimal('0.33')

 

fractions 方法

>>> from fractions import Fraction # Fractions: numerator+denominator
>>> f = Fraction(2, 3)
>>> f + 1
Fraction(5, 3)
>>> f + Fraction(1, 2)
Fraction(7, 6)
In [2]: (2.55).as_integer_ratio()
Out[2]: (2871044762448691, 1125899906842624) # 精算?哈哈~

 

 

四、专业数学计算

四个常用专业库

更是有专业的库提供方案 纯数计算,可能有必要单独篇章总结。

import math
import random
import statistics
import numpy as np

  

高数课程

The math module gives access to the underlying C library functions for floating point math:

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

 

统计课程

The random module provides tools for making random selections:

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

The statistics module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data:

>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095

 

 

 

numpy - Quickstart tutorial


Ref: https://docs.scipy.org/doc/numpy/user/quickstart.html

 

一、矩阵 (Matrix) 

初始化

NumPy’s array class is called ndarray. 若干例子:

# 初始化

>>> import numpy as np

# (1) 描述型初始化
>>> a = np.arange(15).reshape(3, 5) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])

# (2) 直接赋值初始化
a = np.array([2,3,4])            # 一维
b = np.array([(1.5,2,3), (4,5,6)]) # 多维

# (3) 制定初始化
np.zeros( (3,4) )               # 多维
np.ones( (2,3,4), dtype=np.int16 ) # 多维
np.empty( (2,3) ) # 多维
np.arange( 10, 30, 5 ) # 一维:均匀点-间隔法
np.linspace( 0, 2, 9 ) # 一维:均匀点-个数法
See also
numpy.random.randnumpy.random.randn
fromfunctionfromfile 

------------------------------------
# 形状和维度
>>>a.shape (3, 5) >>>a.ndim 2

>>> a.size 15

------------------------------------
# 内部成员属性
>>> type(a)
<type 'numpy.ndarray'>

>>> a.dtype.name
'int64'

>>> a.itemsize
8

 

Basic Operations

满足基本的矩阵性质,略。

>>> import numpy as np
>>> a = np.arange(15).reshape(3,5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> b = np.arange(15).reshape(3,5)
>>> a*b
array([[  0,   1,   4,   9,  16],
       [ 25,  36,  49,  64,  81],
       [100, 121, 144, 169, 196]])

 

Universal Functions

Available: https://numpy.org/devdocs/user/quickstart.html

allanyapply_along_axis 矩阵对比,元素全一样 只要有一个一样 lamdba 处理某维元素
argmaxargminargsortaveragebincount 第几维的最大值 第几维的最小值 某一维排序 某一维均值  基数排序
ceilclipconjcorrcoefcov 取右 "天花板" 设置“左右天花板” 求共轭 协方差[-1, 1] 协方差
crosscumprodcumsumdiffdot 向量积 累积乘 累计加 相邻元素差值 点积
floorinnerinvlexsortmax 取左 "地板” 类似“点积” 逆矩阵 向量排序 向量中的最大值
maximummeanmedianminminimum 向量中元素与一个值的最大值 mean
median 向量中的最小值 向量中元素与一个值的最小值
nonzeroouterprodreround 非零元素的所有坐标 向量1的各元素与向量2相乘  元素的乘积 正则  四舍五入
sortstdsumtracetranspose 按照某一个维度排序 计算全局标准差 某维度求和   对角线元素的和  矩阵转置
varvdotvectorizewhere  方差 点积  将函数向量化: lamdba 符合某一条件的下标函数  

 

Here is a list of some useful NumPy functions and methods names ordered in categories. See Routines for the full list.

Array Creation arangearraycopyemptyempty_likeeyefromfilefromfunctionidentitylinspacelogspacemgridogridonesones_likerzeroszeros_like
Conversions ndarray.astypeatleast_1datleast_2datleast_3dmat
Manipulations array_splitcolumn_stackconcatenatediagonaldsplitdstackhsplithstackndarray.itemnewaxisravelrepeatreshaperesizesqueezeswapaxestaketransposevsplit,vstack
Questions allanynonzerowhere
Ordering argmaxargminargsortmaxminptpsearchsortedsort
Operations choosecompresscumprodcumsuminnerndarray.fillimagprodputputmaskrealsum
Basic Statistics covmeanstdvar
Basic Linear Algebra crossdotouterlinalg.svdvdot


二、矩阵操作

矩阵下标

index 表示范围

#coding:utf-8
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a.shape)      #(2,3)
print(a[:][0])      #这样写,无论前后,只遍历第一行
print(a[0][:])
print(a[:][1])
print(a[1][:])
############################
print(a[:,0])      #这样写才是遍历第一列,前后有区别
print(a[0,:])
print(a[:,1])
print(a[1,:])
print(a[:,2])
############################
print(a[0:3][0])    #[:]范围明明是3个,拆开写就不对,要符合实际情况
print(a[0][0])
print(a[1][0])

 

下标表示范围内的“间隔”

>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])

 

矩阵遍历

传统遍历 - 规则数组 

list2d = [[1,2,3],[4,5,6]]
sum = 0
for i in range(len(list2d)):
    for j in range(len(list2d[0])):
        sum += list2d[i][j]

 

句柄遍历 - 不规则数组

list2d = [[1,2,3],[4,5]]
sum = 0
for i in list2d:
    for j in i:
        sum += j

 

矩阵取整

取左地板值

# np.floor取整
>>> a = np.floor(10*np.random.random((3,4))) >>> a array([[ 2., 8., 0., 6.], [ 4., 5., 1., 1.], [ 8., 9., 3., 6.]]) >>> a.shape (3, 4)

 

仅保留整数位

math.trunc(-2.5) 更人性化,return -2; 而不是floor的-3。

 

四舍五入

round(2.45):四舍五入

 

 

三、矩阵形变

扁平化

完全扁平

>>> a.ravel()  # returns the array, flattened
array([ 2.,  8.,  0.,  6.,  4.,  5.,  1.,  1.,  8.,  9.,  3.,  6.])

 

自定义扁平

>>> a.reshape(6,2)  # returns the array with a modified shape
array([[ 2.,  8.],
       [ 0.,  6.],
       [ 4.,  5.],
       [ 1.,  1.],
       [ 8.,  9.],
       [ 3.,  6.]])

-----------------------------------------------------------------------

>>> a.resize((2,6))  # this method modifies the array itself!
>>> a
array([[ 2.,  8.,  0.,  6.,  4.,  5.],
       [ 1.,  1.,  8.,  9.,  3.,  6.]])

 

转置

>>> a.T  # returns the array, transposed
array([[ 2.,  4.,  8.],
       [ 8.,  5.,  9.],
       [ 0.,  1.,  3.],
       [ 6.,  1.,  6.]])
>>> a.T.shape
(4, 3)
>>> a.shape
(3, 4)

    

堆叠

整体对接

Stacking together different arrays.

>>> a = np.floor(10*np.random.random((2,2)))
>>> a
array([[ 8.,  8.],
       [ 0.,  0.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[ 1.,  8.],
       [ 0.,  4.]])

>>> np.vstack((a,b))  # 第一维度的粘结,更深 array([[ 8., 8.], [ 0., 0.], [ 1., 8.], [ 0., 4.]])
>>> np.hstack((a,b))  # 第二维度的对接,更宽 array([[ 8., 8., 1., 8.], [ 0., 0., 0., 4.]])

 

各取出一个配对

column_stack & row_stack.

>>> np.hstack([np.array([1, 2, 3]), np.array([4, 5, 6])])
array([1, 2, 3, 4, 5, 6])

>>> np.column_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])  # 按照列的顺序,各自拿出一个,组合在一起
array([[1, 4],
       [2, 5],
       [3, 6]])
>>> np.vstack([np.array([1, 2, 3]), np.array([4, 5, 6])])
array([[1, 2, 3],
       [4, 5, 6]])

>>> np.row_stack([np.array([1, 2, 3]), np.array([4, 5, 6])])    # 按照行的顺序,各自拿出一个,组合在一起
array([[1, 2, 3],
       [4, 5, 6]])

  

元素自增加一维度

>>> from numpy import newaxis
>>> a = np.array([4.,2.]) >>> b = np.array([2.,8.])
>>> a[: ,newaxis] # This allows to have a 2D columns vector array([[ 4.], [ 2.]])   # 可见,自增加了维度的效果

>>> np.column_stack((a[:,newaxis],b[:,newaxis]))  // 两个一维数组的合并和两个数字合并,本质上是一样的:因为一个数字其实就是“默认一维” array([[ 4., 2.], [ 2., 8.]])

>>> np.vstack((a[:,newaxis],b[:,newaxis])) # The behavior of vstack is different array([[ 4.], [ 2.], [ 2.], [ 8.]])

 

拆分

注意:可以通过定义 “分割点” 来分割高维矩阵。

Splitting one array into several smaller ones.

>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ 9.,  5.,  6.,  3.,  6.,  8.,  0.,  7.,  9.,  7.,  2.,  7.],
       [ 1.,  4.,  9.,  2.,  2.,  1.,  0.,  6.,  2.,  2.,  4.,  0.]])

>>> np.hsplit(a,3)   # Split a into 3
[array([[ 9.,  5.,  6.,  3.], [ 1.,  4.,  9.,  2.]]), 
array([[ 6., 8., 0., 7.], [ 2., 1., 0., 6.]]),
array([[ 9., 7., 2., 7.], [ 2., 2., 4., 0.]])]
>>> np.hsplit(a, (3,4)) # Split a after the third and the fourth column 看样子像是"分割点" [array([[ 9., 5., 6.], [ 1., 4., 9.]]), array([[ 3.], [ 2.]] ), array([[ 6., 8., 0., 7., 9., 7., 2., 7.], [ 2., 1., 0., 6., 2., 2., 4., 0.]])] >>> np.vsplit(a,(3,4)) [array([[ 2., 9., 0., 4., 3., 2., 8., 0., 6., 2., 0., 4.], [ 8., 0., 5., 3., 4., 9., 5., 0., 3., 4., 4., 5.]]), array([], shape=(0, 12), dtype=float64), array([], shape=(0, 12), dtype=float64)]

 

np.split更灵活,任意分割!

>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10]) [array([ 0., 1., 2.]), array([ 3., 4.]), array([ 5.]), array([ 6., 7.]), array([], dtype=float64)]

其他:numpy.array_split 【似乎用处不大】

 

 

四、矩阵拷贝

引用,非拷贝

No Copy at All, 引用

>>> b = a            # no new object is created
>>> id(a)            # id is a unique identifier of an object

 

映射关系 view

虽 id 不同,但base指向对方。

view矩阵虽然形状变了,但每个元素还是跟原来的“有映射关系”,改变某值,对应的"原位置的值"改变。

>>> c = a.view()
>>> c is a
False
>>> c.base is a                        # c is a view of the data owned by a <---- 理解这句话!
True
>>> c.flags.owndata False
>>> c.shape = 2,6 # a's shape doesn't change >>> a.shape (3, 4) >>> c[0,4] = 1234 # a's data changes >>> a array([[ 0, 1, 2, 3], [1234, 5, 6, 7], [ 8, 9, 10, 11]])

 

Deep Copy , 深拷贝

>>> d = a.copy()                          # a new array object with new data is created
>>> d is a
False
>>> d.base is a                           # d doesn't share anything with a
False
>>> d[0,0] = 9999
>>> a
array([[   0,   10,   10,    3],
       [1234,   10,   10,    7],
       [   8,   10,   10,   11]])

 

 

五、统计采样

Ref: Numpy随机抽样

 

正态分布

#均匀分布
np.random.rand(2,5)  // shape

#正态分布
np.random.randn(1,10) // shape

#均匀分布 - 半开半闭区间 - 整数 【nice】
np.random.randint(2, 5, 10)       // interval
np.random.randint(2, 5, (6,6))    // interval

#均匀分布 - 闭区间 - 整数 【nice】
np.random.random_integers(2, 5, 10)

#均匀分布 - 半开半闭区间 - 百分比
np.random.random_sample((6,6))

#均匀分布 - 闭区间 - 整数
np.random.choice(10, 5)

  

其他分布

random.beta(a,b,size):从 Beta 分布中生成随机数。
random.binomial(n, p, size):从二项分布中生成随机数。
random.chisquare(df,size):从卡方分布中生成随机数。
random.dirichlet(alpha,size):从 Dirichlet 分布中生成随机数。
random.exponential(scale,size):从指数分布中生成随机数。
random.f(dfnum,dfden,size):从 F 分布中生成随机数。
random.gamma(shape,scale,size):从 Gamma 分布中生成随机数。
random.geometric(p,size):从几何分布中生成随机数。
random.gumbel(loc,scale,size):从 Gumbel 分布中生成随机数。
random.hypergeometric(ngood, nbad, nsample, size):从超几何分布中生成随机数。
random.laplace(loc,scale,size):从拉普拉斯双指数分布中生成随机数。
random.logistic(loc,scale,size):从逻辑分布中生成随机数。
random.lognormal(mean,sigma,size):从对数正态分布中生成随机数。
random.logseries(p,size):从对数系列分布中生成随机数。
random.multinomial(n,pvals,size):从多项分布中生成随机数。
random.multivariate_normal(mean, cov, size):从多变量正态分布绘制随机样本。
random.negative_binomial(n, p, size):从负二项分布中生成随机数。
random.noncentral_chisquare(df,nonc,size):从非中心卡方分布中生成随机数。
random.noncentral_f(dfnum, dfden, nonc, size):从非中心 F 分布中抽取样本。
random.normal(loc,scale,size):从正态分布绘制随机样本。
random.pareto(a,size):从具有指定形状的 Pareto II 或 Lomax 分布中生成随机数。
random.poisson(lam,size):从泊松分布中生成随机数。
random.power(a,size):从具有正指数 a-1 的功率分布中在 0,1 中生成随机数。
random.rayleigh(scale,size):从瑞利分布中生成随机数。
random.standard_cauchy(size):从标准 Cauchy 分布中生成随机数。
random.standard_exponential(size):从标准指数分布中生成随机数。
random.standard_gamma(shape,size):从标准 Gamma 分布中生成随机数。
random.standard_normal(size):从标准正态分布中生成随机数。
random.standard_t(df,size):从具有 df 自由度的标准学生 t 分布中生成随机数。
random.triangular(left,mode,right,size):从三角分布中生成随机数。
random.uniform(low,high,size):从均匀分布中生成随机数。
random.vonmises(mu,kappa,size):从 von Mises 分布中生成随机数。
random.wald(mean,scale,size):从 Wald 或反高斯分布中生成随机数。
random.weibull(a,size):从威布尔分布中生成随机数。
random.zipf(a,size):从 Zipf 分布中生成随机数。

再结合取整即可:np.floor(<list>) 

   

End.

posted @ 2018-01-19 15:10  郝壹贰叁  阅读(385)  评论(0编辑  收藏  举报