散亂2

zip():

alst=['1','2','3']

blst=['a','b','c']

for z1,z2 in zip(alst,blst):
    print(z1,z2)


1 a
2 b
3 c

 

 

#enumerate()列舉,枚舉:

alst=['a','c','b','f']

for index,value in enumerate(alst):
    print(index,value)


0 a
1 c
2 b
3 f

可通過start參數自定義開始列舉的序號數字,

for index,value in enumerate(alst,start=10):
    print(index,value)


10 a
11 c
12 b
13 f

 

iterating over file connections:

file=open('file.txt')
it=iter(file)
print(next(it))
輸出:第一行
print(next(it))
輸出:第二行

 

定義函數:

def jj(x,y):
    z=x**y
    h=y**x
    ttuple=(z,h)
    return ttuple

jj(3,2)
Out[8]: (9, 8)

type(jj(3,2))
Out[9]: tuple

 

定義函數時,添加參數默認值:
def power(number,pow=1):
    new_value=number**pow
    return new_value

 

def hh(x,y=2):
    return x**y

hh(8)
Out[11]: 64

hh(9,3)
Out[12]: 729

 

定義函數時,多重參數:

def ff(*y):
    jj=1
    for x in y:
        jj=jj*x
    return jj

ff(3,4,5)
Out[14]: 60

 

 

plt.yticks([0,2,4,6,8,10],['0萬','2萬','4萬','6萬','8萬','10萬']

 

import pandas as pd
adf=pd.DataFrame({'a':[3,5,2],'b':['78','23','11']})
adf['c']=adf.b.apply(len)

adf
Out[43]: 
   a   b  c
0  3  78  2
1  5  23  2
2  2  11  2

 

索引可自定義名稱:

adf.index.name='inx'

adf
Out[46]: 
     a   b  c
inx          
0    3  78  2
1    5  23  2
2    2  11  2

 

 

iterrows():

for index,rows in adf.iterrows():
    print(index)
    print(rows)


0
a     3
b    78
c     2
Name: 0, dtype: object
1
a     5
b    23
c     2
Name: 1, dtype: object
2
a     2
b    11
c     2
Name: 2, dtype: object
 

這裏的iterrows()返回值爲元組,(index,row)

上面的代碼裏,for循環定義了兩個變量,index,row,那麼返回的元組,index=index,row=row.

 

如果for循環時,只定義一個變量:

for rows in adf.iterrows():
    print(rows)

那麼row就是整個元組。輸出結果可以看出:
(0, a     3
b    78
c     2
Name: 0, dtype: object)
(1, a     5
b    23
c     2
Name: 1, dtype: object)
(2, a     2
b    11
c     2
Name: 2, dtype: object)

 

Python map() 函數:

map()是 Python 內置的高階函數,它接收一個函數 f 和一個 list, 並通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。

map() 會根據提供的函數對指定序列做映射。

第一個參數 function 以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表。

map() 函數語法:

map(function, iterable, ...)

參數
function -- 函數
iterable -- 一個或多個序列
返回值
Python 3.x 返回迭代器。


>>>def square(x) :            # 計算平方數
...     return x ** 2
... 
>>> list(map(square, [1,2,3,4,5]))   # 計算列表各個元素的平方
[1, 4, 9, 16, 25]
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))  # 使用 lambda 匿名函數
[1, 4, 9, 16, 25]
 
# 提供了兩個列表,對相同位置的列表數據進行相加
>>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[3, 7, 11, 15, 19]


 

廣播允許這些二進制操作可以用於不同大小的數組。例如,可以簡單地將一個標量(可以認爲是一個零維的數組)和一個數組相加:
aa=np.arange(1,5)
aa+8
Out[19]: array([ 9, 10, 11, 12])


對兩個數組的同時廣播:
a=np.arange(3)
b=np.arange(3)[:,np.newaxis]

a+b
Out[22]: 
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

正如此前將一個值擴展或廣播以匹配另外一個數組的形狀,這裏將a和b都進行了擴展來匹配一個公共的形狀,最終的結果是一個二維數組。

 

Numpy數組按行或按列歸一化:
給定一個數組,將各列(行)歸一化(縮放到 [0,1] )
所謂(0,1)歸一化,就是通過遍歷feature vector裏的每一個特徵值的數據,將Max和Min的記錄下來,並通過Max-Min作爲基數(即Min=0,Max=1)進行數據的歸一化處理。

通過從X數組的元素中減去這個均值實現歸一化,X_centered=X-Xmean;爲了進一步覈對我們的處理是否正確,可以查看歸一化的數組的均值是否接近0;

 

 

Conditionals in generator expressions:
列表:
alist=[x for x in range(10) if x%2==0]

alist    
Out[2]: [0, 2, 4, 6, 8]

元組:
alist=(x for x in range(10) if x%2==0)

alist    
Out[4]: <generator object <genexpr> at 0x0000000008F231B0>

list(alist)    
Out[5]: [0, 2, 4, 6, 8]

Conditionals in comprehensions:
[num**2 if num%2==0 else 0 for num in range(10)]
Out[6]: [0, 0, 4, 0, 16, 0, 36, 0, 64, 0]

 

Dict comprehensions:
a={num:-num for num in range(5)}

print(a)
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4}

print(type(a))
<class 'dict'>

 

np.dot():

np.dot()函數主要有兩個功能,向量點積和矩陣乘法,這裏我就簡單列舉了三種最常用到的情況

1. np.dot(a, b), 其中a爲一維的向量,b爲一維的向量,當然這裏a和b都是np.ndarray類型的, 此時因爲是一維的所以是向量點積。

import numpy as np
 
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
print(np.dot(a, b))
 
output:
130
[Finished in 0.2s]
2. np.dot(a, b), 其中a爲二維矩陣,b爲一維向量,這時b會被當做一維矩陣進行計算

import numpy as np
 
a = np.random.randint(0,10, size = (5,5))
b = np.array([1,2,3,4,5])
print("the shape of a is " + str(a.shape))
print("the shape of b is " + str(b.shape))
print(np.dot(a, b))
 
 
output:
the shape of a is (5, 5)
the shape of b is (5,)
[42 85 50 81 76]
[Finished in 0.2s]
這裏需要注意的是一維矩陣和一維向量的區別,一維向量的shape是(5, ), 而一維矩陣的shape是(5, 1), 若兩個參數a和b都是一維向量則是計算的點積,但是當其中有一個是矩陣時(包括一維矩陣),dot便進行矩陣乘法運算,同時若有個參數爲向量,會自動轉換爲一維矩陣進行計算。

 

3. np.dot(a ,b), 其中a和b都是二維矩陣,此時dot就是進行的矩陣乘法運算

import numpy as np
 
a = np.random.randint(0, 10, size = (5, 5))
b = np.random.randint(0, 10, size = (5, 3))
print("the shape of a is " + str(a.shape))
print("the shape of b is " + str(b.shape))
print(np.dot(a, b))
 
 
output:
the shape of a is (5, 5)
the shape of b is (5, 3)
[[ 66  80  98]
 [ 53  60  60]
 [ 65  84  85]
 [ 25 113 101]
 [ 42  78  77]]
[Finished in 0.2s]
--------------------- 
 

 

數組的轉置:
a=np.arange(15).reshape((3,5))

a
Out[29]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

a.T
Out[30]: 
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])

 

 

np.newaxis,增加維度:

import numpy as np

andarray=np.linspace(1, 10, 10)

andarray.shape
Out[3]: (10,)

andarray
Out[4]: array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])

bndarray=andarray[:,np.newaxis]

bndarray
Out[6]: 
array([[ 1.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 5.],
       [ 6.],
       [ 7.],
       [ 8.],
       [ 9.],
       [10.]])

bndarray.shape
Out[7]: (10, 1)

cndarray=andarray[np.newaxis,:]

cndarray.shape
Out[9]: (1, 10)

cndarray
Out[10]: array([[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]])

np.random.randint(1,100,size=(10,1))
Out[11]: 
array([[98],
       [92],
       [81],
       [ 2],
       [16],
       [60],
       [12],
       [37],
       [49],
       [ 5]])

np.random.randint(1,100,size=(1,10))
Out[12]: array([[51, 49, 55,  7, 44,  9, 26, 16, 92, 38]])

np.random.randint(1,100,size=(5,10))
Out[13]: 
array([[57, 12, 42, 15, 96,  4, 39, 33, 84, 16],
       [91,  4,  5, 34, 71, 62,  5, 48, 65, 10],
       [79, 14, 32, 67, 78, 32, 34, 81, 50, 22],
       [27, 11, 29, 29, 27, 65, 77, 35, 16, 99],
       [65, 45, 95, 27, 53, 63, 30, 31, 52, 55]])

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章