2014-10-07 94 views
-1

給出一個numpy的陣列「x」和跳躍大小「N」,我要創建一個將返回numpy.ndarray用「X」適合跳值的函數尺寸,例如,如果x = [0,1,2,3,4,5,6,7,8,9]和N = 2,則該函數返回輸出= [0,2,4,6,8 ]。到目前爲止,我已經想到以下內容:聲明空numpy.ndarray並填寫

def hopSamples(x,N) 
    i = 0 
    n = len(x) 
    output = numpy.ndarray([]) 
    while i<n: 
     output.append(x[i]) 
     i = i+N 
    return output 

但它給出錯誤。我怎樣才能管理這個?我只是開始Python,所以我肯定會有很多錯誤,所以任何幫助將非常感激!

+2

發佈你得到確切的錯誤將在未來有用,雖然你得到的答案是非常好的。 – porglezomp 2014-10-07 00:49:07

+2

此外,你的問題標題並不真正適合你的問題的描述。爲「聲明(實際上,創建)一個空數組和填充」的方式是'np.zeros'加上正常索引設定。但是你想要做的並不是首先要做的。 – abarnert 2014-10-07 00:50:47

+0

是的,對不起,我現在看到它。我對我在Python方面的知識缺乏表示歉意,上週我開始使用它。謝謝您的意見! – Hec46 2014-10-07 19:02:47

回答

3

你可以用切片:

In [14]: arr = np.arange(0, 10) 

In [15]: arr 
Out[15]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

In [16]: arr[::2] 
Out[16]: array([0, 2, 4, 6, 8]) 

因此,你的函數只會是這樣的:

def hopSamples1(x, N): 
    return x[::N] 

如果您有任何疑問在事先聲明空數組,並使用循環加油吧T,你可以改變你的函數一點做到以下幾點之一。

  • 您可以初始化一個空數組,並在循環的每次迭代中通過另一個單元擴展它。請注意,每次都會創建並返回一個新數組。

    def hopSamples2(x, N): 
        i = 0 
        n = len(x) 
        output = np.empty(shape = 0, dtype = x.dtype) 
        while i < n: 
         output = np.append(output, x[i]) 
         i += N 
        return output 
    
  • 一種替代實現將預先創建整個陣列,但在設置這些值到它的細胞中一個接一個。

    def hopSamples3(x, N): 
        i = 0 
        n = len(x) 
        m = n/N 
        output = np.ndarray(shape = m, dtype = x.dtype) 
        while i < m: 
         output[i] = x[i * N] 
         i += 1 
        return output 
    

一個簡單的基準測試表明,使用切片是同時通過一個擴展陣列一個最快的方法是最慢的:

In [146]: %time hopSamples1(arr, 2) 
CPU times: user 21 µs, sys: 3 µs, total: 24 µs 
Wall time: 28.8 µs 
Out[146]: array([0, 2, 4, 6, 8]) 

In [147]: %time hopSamples2(arr, 2) 
CPU times: user 241 µs, sys: 29 µs, total: 270 µs 
Wall time: 230 µs 
Out[147]: array([0, 2, 4, 6, 8]) 

In [148]: %time hopSamples3(arr, 2) 
CPU times: user 35 µs, sys: 5 µs, total: 40 µs 
Wall time: 45.8 µs 
Out[148]: array([0, 2, 4, 6, 8]) 
+0

非常感謝您的努力!事實上,我可以以任何方式做到這一點,但是我之前對Matlab的知識讓我覺得我解釋的是一個很好的方法,但是那時你們向我展示了我不知道的最簡單的方法,那就是我是如何做到的。所以,非常感謝你! – Hec46 2014-10-07 19:08:24

1

使用numpy的切片,基本上start:stop:step

In [20]: xs 
Out[20]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

In [21]: xs[::2] 
Out[21]: array([0, 2, 4, 6, 8]) 
+0

謝謝!工作正常! – Hec46 2014-10-07 19:03:37

2
import numpy as np 
a = np.array([0,1,2,3,4,5,6,7,8,9,10]) 
print "Please input a step number: " 
N = int(raw_input()) 
b = a[::N] 
print "b is: ", b 
+0

好辦法,謝謝! – Hec46 2014-10-07 19:04:38