0

おはよう専門家、

整数を含む配列があり、配列内の一意の値が特別な順序で並べ替えられたリストがあります。私が欲しいのは、配列内の各値のインデックスを含む別の配列を作成することです。

#a numpy array with integer values
#size_x and size_y: array dimensions of a
#index_list contain the unique values of a sorted in a special order.
#b New array with the index values

for i in xrange(0,size_x):
     for j in xrange(0,size_y):                    
         b[i][j]=index_list.index(a[i][j])

これは機能しますが、実行には長い時間がかかります。それを行うためのより速い方法はありますか?

助けてくれて本当にありがとうございます

ドイツ人

4

2 に答える 2

2

遅い部分はルックアップです

index_list.index(a[i][j])

このタスクにPython辞書を使用する方がはるかに高速です。それよりも

index_list = [ item_0, item_1, item_2, ...]

使用する

index_dict = { item_0:0,  item_1:1, item_2:2, ...}

これは、次を使用して作成できます。

index_dict = dict( (item, i) for i, item in enumerate(index_list) )
于 2012-09-11T09:38:39.440 に答える
1

試しませんでしたが、これは純粋なnumpyであるため、辞書ベースのアプローチよりもはるかに高速であるはずです。

# note that the code will use the next higher value if a value is
# missing from index_list.
new_vals, old_index = np.unique(index_list, return_index=True)

# use searchsorted to find the index:
b_new_index = np.searchsorted(new_vals, a)

# And the original index:
b = old_index[b_new_index]

または、index_listに任意の全体を入力することもできます。


編集されたコード、それ自体は非常に単純に間違っていました(または非常に制限されていました)...

于 2012-09-11T11:14:06.837 に答える