Home > database >  Extend a number of list zero into a multi-dimension array in Python
Extend a number of list zero into a multi-dimension array in Python

Time:05-07

I am new to Python and I am trying to extend an existing list with a list of zero by a number. Below is my code but I believe there is another way to make it simpler and also improve the performance.

missing_len_last_slice = step - len(result_list[-1])
list = []
list_append_zero = np.pad(list, (0, len(list_channels)), 'constant')
for y in range(missing_len_last_slice):
    list.append(list_append_zero)
merge_list_result = np.vstack((result_list[-1], list))
result_list[-1] = merge_list_result

Current:

Length: 5.200

array([[-0.4785, -1.578 ],
       [-0.484 , -1.5815],
       [-0.483 , -1.584 ],
       ...,
       [-0.13  , -0.9475],
       [-0.117 , -0.9315],
       [-0.1175, -0.9395]])

Expectation:

Length: 10.000 with the extension of 4.800 [0, 0]

array([[-0.4785, -1.578 ],
       [-0.484 , -1.5815],
       [-0.483 , -1.584 ],
       ...,
       [-0.13  , -0.9475],
       [-0.117 , -0.9315],
       [-0.1175, -0.9395],
       [0, 0],
       [0, 0],
       ...
       [0, 0]])

PS: The number dimension of the array is dynamic. In the example, it is 2 as [-0.4785, -1.578 ].

CodePudding user response:

As my previous answer you can do this as:

a = np.array([[-0.4785, -1.578 ],
              [-0.484 , -1.5815],
              [-0.483 , -1.584 ]])

pad_fill = np.array([0.0, 0.0])
padding_number = 2              # 10000 - a.shape[0]

A_pad = np.pad(a, ((0, padding_number), (0, 0)), constant_values=pad_fill)
# [[-0.4785 -1.578 ]
#  [-0.484  -1.5815]
#  [-0.483  -1.584 ]
#  [ 0.      0.    ]
#  [ 0.      0.    ]]
  • Related