Lesson 11
Append, Insert, and Delete
Add values with np.append and np.insert and remove them with np.delete, on 1-D arrays and on whole rows or columns of 2-D arrays.
An ndarray has a fixed size. np.append, np.insert, and np.delete never change the array you pass in. Each builds and returns a new one, so assign the result to a name.
np.append
np.append(arr, values) adds values at the end. Without an axis, a 2-D array is flattened first. With axis=0, the new rows must have the same number of columns.
import numpy as np
arr = np.array([11, 2, 6, 7])
longer = np.append(arr, 10)
print(longer)
print(arr)
print(np.append(arr, [20, 30]))
m = np.array([[1, 2], [3, 4]])
print(np.append(m, [[5, 6]]))
print(np.append(m, [[5, 6]], axis=0))Output:
[11 2 6 7 10]
[11 2 6 7]
[11 2 6 7 20 30]
[1 2 3 4 5 6]
[[1 2]
[3 4]
[5 6]]np.insert
np.insert(arr, index, value) puts the value before that index. A list of indices refers to positions in the original array. Add an axis to insert a whole row or column.
import numpy as np
a = np.array([10, 20, 30, 40])
print(np.insert(a, 1, 35))
print(np.insert(a, [1, 3], [15, 35]))
m = np.array([[1, 2], [3, 4]])
print(np.insert(m, 1, [9, 9], axis=0))
print(np.insert(m, 0, 0, axis=1))Output:
[10 35 20 30 40]
[10 15 20 30 35 40]
[[1 2]
[9 9]
[3 4]]
[[0 1 2]
[0 3 4]]np.delete on 1-D
np.delete(arr, index) removes one position. Pass a list to remove several at once.
import numpy as np
arr = np.array([4, 5, 6, 7, 8, 9, 10, 11])
print(np.delete(arr, 2))
print(np.delete(arr, [1, 2, 3]))Output:
[ 4 5 7 8 9 10 11]
[ 4 8 9 10 11]np.delete on 2-D
axis=0 removes rows and axis=1 removes columns. With no axis, the array is flattened first and the index counts across every value.
import numpy as np
m = np.array([[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]])
print(np.delete(m, 1, axis=1))
print(np.delete(m, [2, 3], axis=1))
print(np.delete(m, 0, axis=0))
print(np.delete(m, 2))Output:
[[11 13 14]
[21 23 24]
[31 33 34]]
[[11 12]
[21 22]
[31 32]]
[[21 22 23 24]
[31 32 33 34]]
[11 12 14 21 22 23 24 31 32 33 34]Adding many values
Each np.append copies the whole array. When you collect values one at a time, add them to a list and convert once at the end.
import numpy as np
squares = []
for m in range(1, 6):
squares.append(m * m)
arr = np.array(squares)
print(arr)Output:
[ 1 4 9 16 25]Key takeaways
-
append, insert, and delete return a new array
-
Without an axis, a 2-D array is flattened first
-
axis=0works on rows,axis=1on columns -
Collect many values in a list, then convert once
-
Next: Splitting Arrays
-
Previous: Filtering Arrays
Loading playground…
Check your understanding
Append, Insert, and Delete Quiz
Does np.append change the array you pass in?
1 / 10