python - Array insertion within a loop with NumPy -
is possible perform np.insert() inside python loop. couldn't perform operation.
def insert_missing_values(): index = [1,2,3,5,18,36] indexes in index: np.insert(terror_attacks_per_year, indexes, 0) print('hello %d',indexes) what noticed that, np.insert() function not executed inside loop. recommended way of achieving this?
following output obtained. please note there no '0' values in numpy array.
hello %d 1 hello %d 2 hello %d 3 hello %d 5 hello %d 18 hello %d 36 array([ 1, 2, 2, 2, 7, 45, 77, 99, 73, 159, 175, 65, 66, 77, 27, 85, 117, 49, 30, 39, 59, 29, 3, 9, 30, 99, 144, 105, 81, 35, 3, 4, 12, 10, 7, 1], dtype=int64)
np.insert supports bulk insertion. don't need call in loop. pass list of indices, , that's enough.
try this:
def insert_missing_values(array, indices): return np.insert(array, indices, 0) idx = [1, 2, 3, 5, 18, 36] terror_attacks_per_year = insert_missing_values(terror_attacks_per_year, idx) print (terror_attacks_per_year)
Comments
Post a Comment