2017-06-26 5 views
1

私は研究で大きなデータセットを扱います。リストまたはナンシー配列の特定の要素を複製する

Numpy配列の要素を複製する必要があります。以下のコードはこれを実現していますが、より効率的に操作を実行する関数がNumpyにありますか?

""" 
Example output 
>>> (executing file "example.py") 
Choose a number between 1 and 10: 
2 
Choose number of repetitions: 
9 
Your output array is: 
[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

>>> 
""" 
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

y = int(input('Choose the number you want to repeat (1-10):\n')) 
repetitions = int(input('Choose number of repetitions:\n')) 
output = [] 

for i in range(len(x)): 
    if x[i] != y: 
     output.append(x[i]) 
    else: 
     for j in range(repetitions): 
      output.append(x[i]) 

print('Your output array is:\n', output) 

答えて

2

一つのアプローチは、np.searchsortedで繰り返される要素のインデックスを見つけることであろう。このインデックスを使用して配列の左右をスライスし、その間に繰り返し配列を挿入します。

このように、一つの解決策は次のようになり - 繰り返される回数がy = 5repetitions = 7でみましょう

x = [2, 4, 5, 6, 7, 8, 9, 10] 

-

idx = np.searchsorted(x,y) 
out = np.concatenate((x[:idx], np.repeat(y, repetitions), x[idx+1:])) 

だとしてxでもう少し一般的なサンプルの場合を考えてみましょう。今

、提案コードを使用 - xは常に[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]であることの具体的なケースについて

In [57]: idx = np.searchsorted(x,y) 

In [58]: idx 
Out[58]: 2 

In [59]: np.concatenate((x[:idx], np.repeat(y, repetitions), x[idx+1:])) 
Out[59]: array([ 2, 4, 5, 5, 5, 5, 5, 5, 5, 6, 7, 8, 9, 10]) 

を、我々はそうのような、よりコンパクトな/エレガントな解決策を持っているでしょう -

np.r_[x[:y-1], [y]*repetitions, x[y:]] 
+0

これはまさに私が探していたものです!本当にありがとう! 私はリストをスライスする必要があると思っていましたが、最もエレガントなアプローチではわかりませんでした。 :) – tionichm

+0

@JanCostandius質問に投稿された特定の 'x'のより洗練された解決策については、編集をチェックしてください。 – Divakar

0

numpy.repeat関数があります。

>>> np.repeat(3, 4) 
array([3, 3, 3, 3]) 

>>> x = np.array([[1,2],[3,4]]) 

>>> np.repeat(x, 2) 
array([1, 1, 2, 2, 3, 3, 4, 4]) 

>>> np.repeat(x, 3, axis=1) 
array([[1, 1, 1, 2, 2, 2], 
     [3, 3, 3, 4, 4, 4]]) 

>>> np.repeat(x, [1, 2], axis=0) 
array([[1, 2], 
     [3, 4], 
     [3, 4]]) 
関連する問題