Home > database >  python) update value of array in dictionary and update it
python) update value of array in dictionary and update it

Time:06-10

I want to update 'array' inside the dictionary after doing interpolation.

for example, "array_ex" is a dictionary and has values like below and '0_array' has (6,100) shape while '1_array' has (6,200) shape...

{"0_array": array([[17., 20., 15., ...,  42.,  52.,  32.],
       [24., 33., 19., ..., 100., 120., 90.],
       ...,
       [2.,  3.,  4., ..., 1., 3., 4.],
       [10., 11., 12., ..., 13., 16., 17.]]),
"1_array": array([[20., 20., 15., ...,  42.,  43.,  35.],
       [52., 33., 22., ..., 88., 86., 90.],
       ...,
       [10.,  11.,  17., ..., 71., 23., 24.],
       [34., 44., 28., ..., 42., 43., 17.]])}

I wrote a function for interpolating the array using np.interp. The function interpolates the shape of array (6,100) to (6,200). However, how can I update my array after interpolating? The name of function is "convert_array".

for i,a in array_ex.items():
    for row in a:
        convert_array(row,100,200) #interpolate 100 to 200

I want to get "array_ex" with updated array after interpolation. Thanks.

CodePudding user response:

Start with a dict containing arrays:

In [168]: dict1 = {'one':np.arange(3), 'two':np.ones(3)}

Make a new dict from those arrays, same keys, new arrays:

In [169]: dict2 = {k:v*2 for k,v in dict1.items()}

In [170]: dict1
Out[170]: {'one': array([0, 1, 2]), 'two': array([1., 1., 1.])}

In [171]: dict2
Out[171]: {'one': array([0, 2, 4]), 'two': array([2., 2., 2.])}

Or with a loop more like yours:

In [172]: dict3 = {}
     ...: for k,v in dict1.items():
     ...:     dict3[k] = v.repeat(2)
     ...:     
In [173]: dict3
Out[173]: {'one': array([0, 0, 1, 1, 2, 2]), 'two': array([1., 1., 1., 1., 1., 1.])}

CodePudding user response:

You can use numpy.wehre like below:

for key, val in dct.items():
    dct[key] = np.where(val==100, 200, val)
    
print(dct)

Output:

{'0_array': array([[ 17.,  20.,  15.,  42.,  52.,  32.],
       [ 24.,  33.,  19., 200., 120.,  90.],
       [  2.,   3.,   4.,   1.,   3.,   4.],
       [ 10.,  11.,  12.,  13.,  16.,  17.]]), 
'1_array': array([[20., 20., 15., 42., 43., 35.],
       [52., 33., 22., 88., 86., 90.],
       [10., 11., 17., 71., 23., 24.],
       [34., 44., 28., 42., 43., 17.]])}
  • Related