1

In order to test a wide range of parameters on a single value output, I am creating a multi-dimensional array to store the values. However, in order to update the values accordingly, I need to calculate the positions to be updated. In order to make this fast, I would like to slice a N dimensional array with an N-1 Dimensional Array. For example, if I had a 2D Array: ''' arr = 1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5 '''

and a slicing array: ''' slicer = [2, 3, 1, 3, 5] ''' would it be possible to do something like this:

arr[:slicer] =

1 2 N N N

1 2 3 N N

1 N N N N

1 2 3 N N

1 2 3 4 5

Where N is Nan or Nul or empty.

Is this possible? If not, what is the best/fastest way to achieve the same result?

To be clear, in my ideal world I would be able to do something like this:

arr[:slicer] = arr[:slicer] * update

  • Can you please give us an example, where slicer a 2-D array? It is unclear what you need in case where slicer has more than 1-D. Thank you – Ehsan May 09 '20 at 23:24

2 Answers2

0
arr = ['1 2 3 4 5', '1 2 3 4 5', '1 2 3 4 5', '1 2 3 4 5', '1 2 3 4 5']
slicing_list = [2, 3, 1, 3, 5]
result = ""
arr_len = len(arr)
for st in arr:
    for n in slicing_list:
        result = " ".join(st.split()[:n])
        # the length of the sliced numbers without whitespaces
        result_len = len(st.split()[:n])
        if arr_len>result_len:
            for i in range((arr_len)-result_len):
                result += " N"
        print("result: "+ result)
0

Adapting an idea used in other SO to pad arrays:

In [481]: arr = np.arange(1,6)*np.ones((5,1),int).astype(object)                                       
In [482]: arr                                                                                          
Out[482]: 
array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]], dtype=object)
In [483]: mask = slicer[:,None]<=np.arange(5)                                                          
In [484]: mask                                                                                         
Out[484]: 
array([[False, False,  True,  True,  True],
       [False, False, False,  True,  True],
       [False,  True,  True,  True,  True],
       [False, False, False,  True,  True],
       [False, False, False, False, False]])
In [485]: arr[mask] = None                                                                             
In [486]: arr                                                                                          
Out[486]: 
array([[1, 2, None, None, None],
       [1, 2, 3, None, None],
       [1, None, None, None, None],
       [1, 2, 3, None, None],
       [1, 2, 3, 4, 5]], dtype=object)
hpaulj
  • 221,503
  • 14
  • 230
  • 353