Python學習-Numpy資料處理

來源:互聯網
上載者:User

標籤:python   資料處理   儲存   運算   列表   

引文

標準的python中用list儲存數值,可以當數組使用。但由於列表的元素是任意對象,因此列表中儲存的是對象的指標。對於數值運算來說,這種結構顯然會浪費記憶體和CPU計算時間。

此外,python還提供了array模組,但由於其不支援多維陣列,因此也不適合數值計算。

So,Numpy正好彌補了這些不足,Numpy提供了兩個基本的對象:ndarray和ufunc。ndarray是儲存單一資料類型的多維陣列,而ufunc是能夠對數組進行處理的函數。

匯入方法

import numpy as np

list轉array:採用的是numpy內建的array轉換方法

>>>list=[1,2]>>>_array = np.array(lists)

array轉list: nunpy的array轉list同樣非常方便,直接使用tolist()方法即可

>>>_list = _array.tolist()

使用numpy的random.shuffle方法對給定的一組有序序列生轉換成一個隨機序列

>>>arr = np.arange(1000) #產生一個序列,from 0 to 999>>>np.random.shuffle(arr)

將numpy的數組格式資料以文字格式設定儲存

>>>np.savetxt("a.txt",a,fmt="%d",delimiter=‘\t‘)

將python列錶轉為numpy格式:

>>>pyList = [5, 11, 122]>>>mat(pyList)

一個例子:

>>> from numpy  import *>>> a = arange(15).reshape(3, 5)>>> aarray([[ 0,  1,  2,  3,  4],       [ 5,  6,  7,  8,  9],       [10, 11, 12, 13, 14]])>>> a.shape(3, 5)>>> a.ndim2>>> a.dtype.name‘int32‘>>> a.itemsize4>>> a.size15>>> type(a)numpy.ndarray>>> b = array([6, 7, 8])>>> barray([6, 7, 8])>>> type(b)numpy.ndarray

數組建立

>>> from numpy import *>>> a = array( [2,3,4] )>>> aarray([2, 3, 4])>>> a.dtypedtype(‘int32‘)>>> b = array([1.2, 3.5, 5.1])>>> b.dtypedtype(‘float64‘)

比較兩種建立方式,其中第一種是錯誤的

>>> a = array(1,2,3,4)    # WRONG>>> a = array([1,2,3,4])  # RIGHT

二維數組建立

>>> b = array( [ (1.5,2,3), (4,5,6) ] )>>> barray([[ 1.5,  2. ,  3. ],       [ 4. ,  5. ,  6. ]])

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Python學習-Numpy資料處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.