2017-06-29 15 views
1

私はこのようなデータフレームがあります。numpy配列のリストに基づいて要素を選択する方法は?

array([[1374495, 3, 'prior', ..., 16.0, 'soy lactosefree', 'dairy eggs'], 
     [3002854, 3, 'prior', ..., 16.0, 'soy lactosefree', 'dairy eggs'], 
     [2710558, 3, 'prior', ..., 16.0, 'soy lactosefree', 'dairy eggs'], 
     ..., 
     [1355976, 206200, 'prior', ..., 16.0, 'soy lactosefree', 
     'dairy eggs'], 
     [1909878, 206200, 'prior', ..., 16.0, 'soy lactosefree', 
     'dairy eggs'], 
     [943915, 206200, 'train', ..., 16.0, 'soy lactosefree', 'dairy eggs']], dtype=object) 

すべての行の最初の数は今、私は配列から行を取得するために使用されるものと受注コードのリストを持っている1374495, 3002854, 2710558...ように、受注コードです。たとえば、使用するリストは[1355976, 1909878, 943915 ]です。配列の中からorderidが[1355976, 1909878, 943915 ]の行を選択する必要があります。効率的にこれを実現するにはどうすればいいですか?

答えて

1

アプローチ#1

ここnp.searchsortedに基づいて一つのアプローチだ -

a[np.in1d(a[:,0], idx)] 
-

def filter_rows(a, idx): 
    # a is input dataframe as array 
    # idx is list of indices for selecting rows 

    a_idx = a[:,0] 
    idx_arr = np.sort(idx) 
    pos_idx = np.searchsorted(idx_arr, a_idx) 
    pos_idx[pos_idx == idx_arr.size] = 0 
    mask = idx_arr[pos_idx] == a_idx 
    out = a[mask] 
    return out 

アプローチ#2

はここnp.in1dと別ですの

サンプルの実行 -

In [83]: a 
Out[83]: 
array([[1374495, 3, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [3002854, 3, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [2710558, 3, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [1355976, 206200, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [1909878, 206200, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [943915, 206200, 'train', 16.0, 'soy lactosefree', 'dairy eggs']]) 

In [84]: idx 
Out[84]: [1355976, 1909878, 943915] 

In [85]: filter_rows(a, idx) 
Out[85]: 
array([[1355976, 206200, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [1909878, 206200, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [943915, 206200, 'train', 16.0, 'soy lactosefree', 'dairy eggs']]) 

In [88]: a[np.in1d(a[:,0], idx)] 
Out[88]: 
array([[1355976, 206200, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [1909878, 206200, 'prior', 16.0, 'soy lactosefree', 'dairy eggs'], 
     [943915, 206200, 'train', 16.0, 'soy lactosefree', 'dairy eggs']]) 
0

numpy_indexedパッケージ(免責事項:私はその作者が午前):

import numpy_indexed as npi 
row_idx = npi.indices(id_column, ids_to_get_index_of) 

がDivakarが提供するソリューションと同じ性能を持つべき操作のこれらのタイプのための効率的な機能が含まれています欠けている値を扱うさまざまな方法を選択するためのkwargsのようないくつかの追加のベルとホイッスルが付属しています。

関連する問題