1. 程式人生 > >學習Python資料分析隨手筆記【三】numpy陣列的函式ix_()

學習Python資料分析隨手筆記【三】numpy陣列的函式ix_()

今天我去圖書館借了一本Python DataAnalysis的書

那今天來說一個關於numpy庫的內容。

當然

課本給出的是著名的lena圖片。不過在pycharm上執行的時候發現它報錯了。隨即就去查看了scipy的檔案搜尋了半天。原來在新版本的scipy中已經將lena移除,不過再細心一看,就發現了一個ascent的檔案。Show一哈子就發現了 lane已經被替換成了

這樣的一個圖片。

Emm好吧 就拿這個圖片試試。

那就介紹一下這次的主要函式吧 ix_函式 這個函式可以為了獲得多元組的結果而用來結合不同向量

那到底是什麼樣子的呢。

參照上面的程式碼如下:

import numpy as np
import

matplotlib.pyplot as plt
import scipy.misc
floor = scipy.misc.ascent()
xmax = floor.shape[
0]
ymax = floor.shape[
1]
def indices(size):
    arr = np.arange(size)
    np.random.shuffle(arr)
#shuffle將序列隨機排序
   
return arr
xin =
indices (xmax)
np.testing.assert_equal(
len(xin),xmax)
yin =
indices (ymax)
np.testing.assert_equal(
len(yin),ymax)
plt.imshow(floor[np.ix_(xin
,yin)])
plt.show()

執行結果如下:

balabalabala

就是這個類似馬賽克東西。

其實這個圖片就是由很多個數組規律的排序而成。

利用numpy.random的子程式包 shuffle()把陣列的元素隨機的索引號重新排列使得陣列產生相應的變化。

然後用ix_()函式重新返回元組並且由imshow把他畫出來

那這個ix_函式到底是個什麼呢?

其實這個函式可以根據多個序列生成一個網格,他需要一個一維陣列作為引數,並且返回一個numpy陣列構成的元祖,至於為什麼是numpy陣列呢?因為他後面帶著個一個大大的array

!!!

至於過程啥樣子呢?

開啟ipython試試

In:ix_([0,1],[1,2])

Out: (array([[0],

       [1]]), array([[1, 2]]))

還有一個就是

np.testing.assert_equal(len(xin),xmax)
這是個什麼東西?查了一下CSDN論壇發現涉及的太少了,去查numpy庫的時候又因為繁多找的我頭昏眼花,於是我決定直接看這個方法的原始碼,嘗試自己理解一下。然鵝。。。。。。

Raises an AssertionError if two objects are not equal.

Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting values.

Parameters
----------
actual : array_like
    The object to check.
desired : array_like
    The expected object.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
    If actual and desired are not equal.

Examples
--------
>>> np.testing.assert_equal([4,5], [4,6])
...
<type 'exceptions.AssertionError'>:
Items are not equal:
item=1
 ACTUAL: 5
 DESIRED: 6

它給了我這樣的解釋。。。好吧不用我自己理解了。顯而易見,這是一個判斷的內容。檢查這個物件所有元素是否相等。畫重點!!!

他還給了一個例子。Examples

   --------

   >>> np.testing.assert_equal([4,5], [4,6])

    ...

   <type 'exceptions.AssertionError'>:

    Itemsare not equal:

   item=1

    ACTUAL: 5

    DESIRED: 6

自己體會!

好了,現在時間20.37不看了。回宿舍打遊戲去了。舍友等著我吃雞呢!