Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: NP.8 Adding elements to arrays

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

Adding elements to arrays

np.append

To add elements to your dataset, you can use np.append

Syntax

np.append(ndarray, elements you want to add, axis)

axis = 0 is row (will be added to the bottom most row)

axis = 1 is column (will be added to right most column)

Adding elements using np.append

Adding 1 element to 1D arrays

Let's start with an array called x and add an integer to the end of the array

Adding multiple elements to 1D arrays

To add more than 1 element, put your elements in a list and append that list to the array

Adding extra rows to 2D arrays

Let's start with a new array y.

To add extra row of elements to y, specify axis = 0 to np.append

Adding extra columns to 2D arrays

To add extra column of elements to y, specify axis = 1.

Note that the syntax between adding rows and columns differs slightly. To add elements to columns, you need to add each element between its own square bracket. 

Exercises

Use this array for the following practice: 

myArray = np.array([[11,12,13], [14,15,16], [17,18,19]])


1. Add a new row of elements containing 20, 21 and 22

2. Add a new column of elements containing 30, 40 and 50

1. Add a new row of elements containing 20, 21 and 22


2. Add a new column of elements containing 30, 40 and 50