Home > Mobile >  Formatting numpy array until it gets to needed length Python
Formatting numpy array until it gets to needed length Python

Time:09-16

How can I write a code where it completes the array a by appending append_val until the length of the array is reached. So the length of a is 6 and the expected length is 10 so it will append append_val until the desired length 10 in this case is reached. How would I be able to do a numpy function that would get me the Expected Output.

import numpy as np 

length = 10
append_val = 0 
a = np.array([12,34,1,3,12,34])

Expected output:

[12,34,1,3,12,34,0,0,0,0]

CodePudding user response:

import numpy as np 

a = np.array([12,34,1,3,12,34])
a.resize(10)
print(a)

CodePudding user response:

I think append_val can change, if this is correct and for example append_val can be one or two or ..., you can try this:

import numpy as np 

length = 10
append_val = 1
a = np.array([12,34,1,3,12,34])

out = []
for i in range(length):
    try:
        out.append(a[i])
    except IndexError:
        out.append(append_val)

print(out)

output:

[12, 34, 1, 3, 12, 34, 1, 1, 1, 1]

CodePudding user response:

If append_val is constant, you could use

a = np.pad(a, (0, length-len(a)), "constant", constant_values=append_val)
  • Related