記錄一些python用法

作者:xg123321123 - 時光雜貨店

出處:http://blog.csdn.net/xg123321123/article/details/54376598

聲明:版權所有,轉載請聯繫作者並註明出處

1 打印數組中所有元素

問題:當數組有大量元素時,想要全部打印出來

解決:

from numpy import *

set_printoptions(threshold='nan')

2 三元表達式

問題:想要用python表達result=5>3?1:0

解決:

1 if 5>3 else 0 ## 爲真時的結果 if 判定條件 else 爲假時的結果  

3 返回數組中符合某一條件的下標

問題:想要用python實現MATLAB中的find函數

解決:

>>a = np.array(a)
>>a
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
>>idx = np.where(a > 2)
>>idx
(array([2, 5, 8], dtype=int32),)
>>a[idx]              
array([3, 3, 3])        
>>a[a>2]              
array([3, 3, 3])  

注:np.where()不接受list類型的參數,另外,np.where()也可用於三目運算的情況:

>>y = np.array([1, 2, 3, 4, 5, 6])  # 將奇數轉換爲偶數,偶數轉換爲奇數
>>y = np.where(y%2 == 0, y+1, y-1)
>>y 

4 遍歷判斷

問題:遍歷的同時,進行判斷

解決:

>>a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>idx = [idx for (idx, val) in enumerate(a) if val > 2]
>>idx
[2, 5, 8]
>>vals = [val for (idx, val) in enumerate(a) if val > 2]
[3, 3, 3]

5 處理NaN

問題:將nan所在的列非nan的均值賦給這些nan值

解決:

>>A = np.array([[1, 2, 3, 4], [5, 6, np.nan, 8], [9, 10, 11, np.nan]])
>>idx = np.where(np.isnan(A))
>>idx
(array([1, 2], dtype=int32), array([2, 3], dtype=int32))
for i in idx:
    A[i[0], i[1]] = A[~np.isnan(A[:, i[1]]), i[1]].mean()

6 隨機數

問題:給出幾個常用的隨機數函數

解決:

>> random.random() #生成一個0到1的隨機符點數: 0 <= n < 1.0
>> random.uniform(a, b) #生成一個指定範圍內的隨機浮點數
>> random.randint(a, b) #生成一個指定範圍內的整數
>> random.choice(sequence) #從序列中獲取一個隨機元素;list, tuple, 字符串都屬於sequence
>> random.randrange([start], stop[, step]) #從指定範圍內,按指定基數遞增的集合中獲取一個隨機數; random.randrange(10, 100, 2)在結果上與 random.choice(range(10, 100, 2)等效
>> random.shuffle(x[, random]) #將一個列表中的元素打亂
>> random.sample(sequence, k) #從指定序列中隨機獲取指定長度的片斷,sample函數不會修改原有序列

7 讀寫文件

問題:幾種讀寫文件的方法

解決:

np.savetxt("result.txt", numpy_data, fmt='%.4f') #將numpy數據保存爲留有4位小數的浮點數,fmt='%.18e'則是保留8位小數的科學計數法

numpy_data = np.loadtxt("result.txt",delimiter=",") #以delimiter爲分隔符讀入數據

file=open('data.txt','w') #保存list數據
file.write(str(list_data));
file.close() 

>> f = file("result.npy", "wb")
>> np.save(f, a) # 順序將a,b,c保存進文件對象f
>> np.save(f, b)
>> np.save(f, c)
>> f.close()
>> f = file("result.npy", "rb")
>> np.load(f) # 順序從文件對象f中讀取內容
array([0, 1, 2, 3, 4, 5, 6, 7])
>> np.load(f)
array([ 0,  1,  3,  6, 10, 15, 21, 28])
>> np.load(f)
array([ 0,  2,  5,  9, 14, 20, 27, 35])

>> [line.strip('\n').strip('\r') for line in open('result.txt')] #返回一個由result.txt構成的list

8 strip()和split()

  • strip()

    • s爲字符串,rm爲要刪除的字符序列,只能刪除開頭或是結尾的字符或字符串;不能刪除中間的字符或字符串

      • s.strip(rm) 刪除s字符串中開頭、結尾處,位於 rm刪除序列的字符

      • s.lstrip(rm) 刪除s字符串中開頭處,位於 rm刪除序列的字符

      • s.rstrip(rm) 刪除s字符串中結尾處,位於 rm刪除序列的字符

    • 當rm爲空時,默認刪除空白符(包括’\n’, ‘\r’, ‘\t’, ’ ‘)
      這裏寫圖片描述
    • 這裏的rm刪除序列是隻要邊(開頭或結尾)上的字符在刪除序列內,就刪除掉
      這裏寫圖片描述
  • split()

    • split返回的是一個列表
    • 不帶參數,默認是空白字符。如下:
      這裏寫圖片描述

    • 按某一個字符/字符串分割
      這裏寫圖片描述

    • 按某一個字符/字符串分割n次
      這裏寫圖片描述

    • 按某一字符/字符串分割n次,並將分割後的字符串/字符賦給新的n+1個變量
      這裏寫圖片描述

9 將數組轉化爲圖片

問題:如題

解決:

>> img = Image.fromarray(image_array) #將image_array數組轉換爲img
>> img.save('outfile.jpg')
>> #上述方法不行的話,還可以嘗試下面的方法
>> import scipy.misc
>> scipy.misc.toimage(image_array, cmin=0.0, cmax=255.0).save('outfile.jpg') #將img_array數組存儲爲outfile.jpg

10 繪製圖像

問題:如題

解決:

>> #imshow()函數格式爲:
>> #matplotlib.pyplot.imshow(X, cmap=None)
>> #X: 要繪製的圖像或數組。
>> #cmap: 顏色圖譜(colormap), 默認繪製爲RGB(A)顏色空間。
>> #還有其它可選的顏色圖譜如:gray,hot,cool等等
>>
>> import matplotlib.pyplot as plt
>> plt.figure(num='astronaut',figsize=(8,8))  #創建一個名爲astronaut的窗口,並設置大小 

>> plt.subplot(2,2,1)     #將窗口分爲兩行兩列四個子圖,則可顯示四幅圖片
>> plt.title('origin image')   #第一幅圖片標題
>> plt.imshow(img)      #繪製第一幅圖片

>> plt.subplot(2,2,2)     #第二個子圖
>> plt.title('R channel')   #第二幅圖片標題
>> plt.imshow(img[:,:,0],plt.cm.gray)      #繪製第二幅圖片,且爲灰度圖
>> plt.axis('off')     #不顯示座標尺寸

>> plt.subplot(2,2,3)     #第三個子圖
>> plt.title('G channel')   #第三幅圖片標題
>> plt.imshow(img[:,:,1],plt.cm.gray)      #繪製第三幅圖片,且爲灰度圖
>> plt.axis('off')     #不顯示座標尺寸

>> plt.subplot(2,2,4)     #第四個子圖
>> plt.title('B channel')   #第四幅圖片標題
>> plt.imshow(img[:,:,2],plt.cm.gray)      #繪製第四幅圖片,且爲灰度圖
>> plt.axis('off')     #不顯示座標尺寸

>> plt.show()   #顯示窗口
>> # 更多詳細用法,見下面引用鏈接

11 格式化輸出dict

問題:如題

解決:

>>#格式化輸出dict
>>import pprint

>>dic = {}
>>for i in xrange(201):
>>    dic[i] = "value for %d" % i

>># 自定義縮進爲4空格
>>pp = pprint.PrettyPrinter(indent=4)
>>pp.pprint(dic)

12 any

  • any(x): 判斷x是否爲空對象,如果都爲空、0、false,或者x直接就是空對象,則返回false,如果不都爲空、0、false,則返回true

  • all(x): 如果x的所有元素都不爲0、”、False, 或者x直接就是空對象,則返回True,否則返回False

13 保存 json 文件

  • 一般情況:
with open("annotation_train_vg.json","w") as f:
    json.dump(your_data,f)
    print("well done...")
  • 有時候會報錯(如下),得自己構造類:
#raise TypeError(repr(o) + " is not JSON serializable")
#TypeError: xx is not JSON serializable

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)


jsObj = json.dumps(your_data, cls=MyEncoder)

fileObject = open('annotation_test_vg.json', 'w')
fileObject.write(jsObj)
fileObject.close()

本篇博客主要整理自
python 中的三元表達式(三目運算符)
Python vs Matlab—— find 與 np.where
Python中的random模塊
numpy矩陣運算和文件存儲
python strip()函數和Split函數的用法總結
python數字圖像處理(5):圖像的繪製

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