python - Replace values of a numpy array by values from another numpy array -
i have 1000 * 1000 numpy array 1 million values created follows :
>>import numpy np >>data = np.loadtxt('space_data.txt') >> print (data) >>[[ 13. 15. 15. ..., 15. 15. 16.] [ 14. 13. 14. ..., 13. 15. 16.] [ 16. 13. 13. ..., 13. 15. 17.] ..., [ 14. 15. 14. ..., 14. 14. 13.] [ 15. 15. 16. ..., 16. 15. 14.] [ 14. 13. 16. ..., 16. 16. 16.]]
i have numpy array which has 2 columns follows:
>> print(key) >>[[ 10., s], [ 11., s], [ 12., s], [ 13., m], [ 14., l], [ 15., s], [ 16., s], ..., [ 92., xl], [ 93., m], [ 94., xl], [ 95., s]]
what want replace each element of of data array corresponding element in second column of key array this..
>> print(data) >>[[ m s s ..., s s s] [ l m l ..., m s s] [ s m m ..., m s xl] ..., [ l s l ..., l l m] [ s s s ..., s s l] [ l m s ..., s s s]]
in python dicts natural choice mapping keys values. numpy has no direct equivalent of dict. have arrays can fast integer indexing. example,
in [153]: keyarray = np.array(['s','m','l','xl']) in [158]: data = np.array([[0,2,1], [1,3,2]]) in [159]: keyarray[data] out[159]: array([['s', 'l', 'm'], ['m', 'xl', 'l']], dtype='|s2')
so if massage key
array 1 looked this:
in [161]: keyarray out[161]: array(['', '', '', '', '', '', '', '', '', '', 's', 's', 's', 'm', 'l', 's', 's', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'xl', 'm', 'xl', 's'], dtype='|s32')
so 10 maps 's' in sense keyarray[10]
equals s
, , forth:
in [162]: keyarray[10] out[162]: 's'
then produce desired result keyarray[data]
.
import numpy np data = np.array( [[ 13., 15., 15., 15., 15., 16.], [ 14., 13., 14., 13., 15., 16.], [ 16., 13., 13., 13., 15., 17.], [ 14., 15., 14., 14., 14., 13.], [ 15., 15 , 16., 16., 15., 14.], [ 14., 13., 16., 16., 16., 16.]]) key = np.array([[ 10., 's'], [ 11., 's'], [ 12., 's'], [ 13., 'm'], [ 14., 'l'], [ 15., 's'], [ 16., 's'], [ 17., 'xl'], [ 92., 'xl'], [ 93., 'm'], [ 94., 'xl'], [ 95., 's']]) idx = np.array(key[:,0], dtype=float).astype(int) n = idx.max()+1 keyarray = np.empty(n, dtype=key[:,1].dtype) keyarray[:] = '' keyarray[idx] = key[:,1] data = data.astype('int') print(keyarray[data])
yields
[['m' 's' 's' 's' 's' 's'] ['l' 'm' 'l' 'm' 's' 's'] ['s' 'm' 'm' 'm' 's' 'xl'] ['l' 's' 'l' 'l' 'l' 'm'] ['s' 's' 's' 's' 's' 'l'] ['l' 'm' 's' 's' 's' 's']]
note data = data.astype('int')
assuming floats in data
can uniquely mapped int
s. appears case data, not true arbitrary floats. example, astype('int')
maps both 1.0 , 1.5 map 1.
in [167]: np.array([1.0, 1.5]).astype('int') out[167]: array([1, 1])
Comments
Post a Comment