728x90
728x90
728x90

상황:

arr는 2d numpy.ndarray

dict_는 dictionary, arr의 각 원소를 변환시킬 mapping

 

1.

res = np.vectorize(dict_.__getitem__)(arr)

np.vectorize는 내부적으로는 결국 python loop방식으로 돌기 때문에 numpy의 C base speedup 이점을 얻기 힘들다.

 

2.

u, inv = np.unique(arr, return_inverse=True)

res = np.array([dict_[x] for x in u])[inv].reshape(a.shape)

이는 [inv]와 reshape에서 numpy의 speedup이점을 얻을 수가 있다.

 

3. 만약 dict_의 key에 arr에 특정 원소만 존재한다면?

 

(1) arr의 일부 원소는 변환하고, 일부는 default값으로 바꿔 넣고 싶다면

u, inv = np.unique(arr, return_inverse=True)

res = np.array([dict_.get(x, "DEFAULT") for x in u])[inv].reshape(a.shape)

이렇게 dict_의 get method로 변환하고, missing key에 대해선 default 입력 가능

 

(2) arr의 일부 원소는 변환하고, 일부는 원래 그대로 두고 싶다면

u, inv = np.unique(arr, return_inverse=True)

res = np.array([dict_.get(x, x) for x in u])[inv].reshape(a.shape)

이렇게 dict_의 get method로 변환하고, missing key에 대해선 원본 그대로 입력 가능

728x90

+ Recent posts