Adding and removing data

Introduzione a NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Concatenating in NumPy

 

 

Two arrays being added together to form one array with elements of both

Introduzione a NumPy

Concatenating rows

classroom_ids_and_sizes = np.array([[1, 22], [2, 21], [3, 27], [4, 26]])
new_classrooms = np.array([[5, 30], [5, 17]])

np.concatenate((classroom_ids_and_sizes, new_classrooms))
array([[ 1, 22],
       [ 2, 21],
       [ 3, 27],
       [ 4, 26],
       [ 5, 30],
       [ 5, 17]])
  • np.concatenate() concatenates along the first axis by default.
Introduzione a NumPy

Concatenating columns

classroom_ids_and_sizes = np.array([[1, 22], [2, 21], [3, 27], [4, 26]])
grade_levels_and_teachers = np.array([[1, "James"], [1, "George"], [3,"Amy"],
                                      [3, "Meehir"]])
np.concatenate((classroom_ids_and_sizes, grade_levels_and_teachers), axis=1)
array([['1', '22', '1', 'James'],
       ['2', '21', '1', 'George'],
       ['3', '27', '3', 'Amy'],
       ['4', '26', '3', 'Meehir']])
Introduzione a NumPy

Shape compatibility

A three by three array and a four by two array which throw a value error when concatenated due to shape incompatibility

Two arrays being added together to form one array with elements of both

Introduzione a NumPy

Dimension compatibility

  A three by three array and a 1D array of three elements which are not compatible dimension and throw a value error

  A three by three array and a three by one array which are compatible in both shape and dimension

Introduzione a NumPy

Creating compatibility

array_1D = np.array([1, 2, 3])
column_array_2D = array_1D.reshape((3, 1))
column_array_2D
array([[1],
       [2],
       [3]])
row_array_2D = array_1D.reshape((1, 3))
row_array_2D
array([[1, 2, 3]])
Introduzione a NumPy

Concatenating new dimensions

Graphic of two 2D arrays being stacked on top of each other to create a 3D array

Graphic which calls out this operation cannot be done with np.concatenate()

Introduzione a NumPy

Deleting with np.delete()

classroom_data
array([['1', '22', '1', 'James'],
       ['2', '21', '1', 'George'],
       ['3', '27', '3', 'Amy'],
       ['4', '26', '3', 'Meehir']],)
np.delete(classroom_data, 1, axis=0)
array([['1', '22', '1', 'James'],
       ['3', '27', '3', 'Amy'],
       ['4', '26', '3', 'Meehir']])
Introduzione a NumPy

Deleting columns

np.delete(classroom_data, 1, axis=1)
array([['1', '1', 'James'],
       ['2', '1', 'George'],
       ['3', '3', 'Amy'],
       ['4', '3', 'Meehir']]')
Introduzione a NumPy

Deleting without an axis

classroom_data
array([['1', '22', '1', 'James'],
       ['2', '21', '1', 'George'],
       ['3', '27', '3', 'Amy'],
       ['4', '26', '3', 'Meehir']],)
np.delete(classroom_data, 1)
array(['1', '1', 'James', '2', '21', '1', 'George', '3', '27', '3', 'Amy',
       '4', '26', '3', 'Meehir'])
Introduzione a NumPy

Let's practice!

Introduzione a NumPy

Preparing Video For Download...