# How to Index, Slice and Reshape NumPy Arrays for Machine Learning

Last Updated on

Machine learning data is represented as arrays.

In Python, data is almost universally represented as NumPy arrays.

If you are new to Python, you may be confused by some of the pythonic ways of accessing data, such as negative indexing and array slicing.

In this tutorial, you will discover how to manipulate and access your data correctly in NumPy arrays.

After completing this tutorial, you will know:

• How to convert your list data to NumPy arrays.
• How to access data using Pythonic indexing and slicing.
• How to resize your data to meet the expectations of some machine learning APIs.

Discover vectors, matrices, tensors, matrix types, matrix factorization, PCA, SVD and much more in my new book, with 19 step-by-step tutorials and full source code.

Let’s get started.

• Update Jul/2019: Fixed small typo related to reshaping 1D data (thanks Rodrigue). How to Index, Slice and Reshape NumPy Arrays for Machine Learning in Python
Photo by Björn Söderqvist, some rights reserved.

## Tutorial Overview

This tutorial is divided into 4 parts; they are:

1. From List to Arrays
2. Array Indexing
3. Array Slicing
4. Array Reshaping

### Need help with Linear Algebra for Machine Learning?

Take my free 7-day email crash course now (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

## 1. From List to Arrays

For examples, see the post:

This section assumes you have loaded or generated your data by other means and it is now represented using Python lists.

Let’s look at converting your data in lists to NumPy arrays.

### One-Dimensional List to Array

You can convert a one-dimensional list of data to an array by calling the array() NumPy function.

Running the example converts the one-dimensional list to a NumPy array.

### Two-Dimensional List of Lists to Array

It is more likely in machine learning that you will have two-dimensional data.

That is a table of data where each row represents a new observation and each column a new feature.

Perhaps you generated the data or loaded it using custom code and now you have a list of lists. Each list represents a new observation.

You can convert your list of lists to a NumPy array the same way as above, by calling the array() function.

Running the example shows the data successfully converted.

## 2. Array Indexing

Once your data is represented using a NumPy array, you can access it using indexing.

Let’s look at some examples of accessing data via indexing.

### One-Dimensional Indexing

Generally, indexing works just like you would expect from your experience with other programming languages, like Java, C#, and C++.

For example, you can access elements using the bracket operator [] specifying the zero-offset index for the value to retrieve.

Running the example prints the first and last values in the array.

Specifying integers too large for the bound of the array will cause an error.

Running the example prints the following error:

One key difference is that you can use negative indexes to retrieve values offset from the end of the array.

For example, the index -1 refers to the last item in the array. The index -2 returns the second last item all the way back to -5 for the first item in the current example.

Running the example prints the last and first items in the array.

### Two-Dimensional Indexing

Indexing two-dimensional data is similar to indexing one-dimensional data, except that a comma is used to separate the index for each dimension.

This is different from C-based languages where a separate bracket operator is used for each dimension.

For example, we can access the first row and the first column as follows:

Running the example prints the first item in the dataset.

If we are interested in all items in the first row, we could leave the second dimension index empty, for example:

This prints the first row of data.

## 3. Array Slicing

So far, so good; creating and indexing arrays looks familiar.

Now we come to array slicing, and this is one feature that causes problems for beginners to Python and NumPy arrays.

Structures like lists and NumPy arrays can be sliced. This means that a subsequence of the structure can be indexed and retrieved.

This is most useful in machine learning when specifying input variables and output variables, or splitting training rows from testing rows.

Slicing is specified using the colon operator ‘:’ with a ‘from‘ and ‘to‘ index before and after the column respectively. The slice extends from the ‘from’ index and ends one item before the ‘to’ index.

Let’s work through some examples.

### One-Dimensional Slicing

You can access all data in an array dimension by specifying the slice ‘:’ with no indexes.

Running the example prints all elements in the array.

The first item of the array can be sliced by specifying a slice that starts at index 0 and ends at index 1 (one item before the ‘to’ index).

Running the example returns a subarray with the first element.

We can also use negative indexes in slices. For example, we can slice the last two items in the list by starting the slice at -2 (the second last item) and not specifying a ‘to’ index; that takes the slice to the end of the dimension.

Running the example returns a subarray with the last two items only.

### Two-Dimensional Slicing

Let’s look at the two examples of two-dimensional slicing you are most likely to use in machine learning.

#### Split Input and Output Features

It is common to split your loaded data into input variables (X) and the output variable (y).

We can do this by slicing all rows and all columns up to, but before the last column, then separately indexing the last column.

For the input features, we can select all rows and all columns except the last one by specifying ‘:’ for in the rows index, and :-1 in the columns index.

For the output column, we can select all rows again using ‘:’ and index just the last column by specifying the -1 index.

Putting all of this together, we can separate a 3-column 2D dataset into input and output data as follows:

Running the example prints the separated X and y elements. Note that X is a 2D array and y is a 1D array.

#### Split Train and Test Rows

It is common to split a loaded dataset into separate train and test sets.

This is a splitting of rows where some portion will be used to train the model and the remaining portion will be used to estimate the skill of the trained model.

This would involve slicing all columns by specifying ‘:’ in the second dimension index. The training dataset would be all rows from the beginning to the split point.

The test dataset would be all rows starting from the split point to the end of the dimension.

Putting all of this together, we can split the dataset at the contrived split point of 2.

Running the example selects the first two rows for training and the last row for the test set.

## 4. Array Reshaping

After slicing your data, you may need to reshape it.

For example, some libraries, such as scikit-learn, may require that a one-dimensional array of output variables (y) be shaped as a two-dimensional array with one column and outcomes for each row.

Some algorithms, like the Long Short-Term Memory recurrent neural network in Keras, require input to be specified as a three-dimensional array comprised of samples, timesteps, and features.

It is important to know how to reshape your NumPy arrays so that your data meets the expectation of specific Python libraries. We will look at these two examples.

### Data Shape

NumPy arrays have a shape attribute that returns a tuple of the length of each dimension of the array.

For example:

Running the example prints a tuple for the one dimension.

A tuple with two lengths is returned for a two-dimensional array.

Running the example returns a tuple with the number of rows and columns.

You can use the size of your array dimensions in the shape dimension, such as specifying parameters.

The elements of the tuple can be accessed just like an array, with the 0th index for the number of rows and the 1st index for the number of columns. For example:

Running the example accesses the specific size of each dimension.

### Reshape 1D to 2D Array

It is common to need to reshape a one-dimensional array into a two-dimensional array with one column and multiple arrays.

NumPy provides the reshape() function on the NumPy array object that can be used to reshape the data.

The reshape() function takes a single argument that specifies the new shape of the array. In the case of reshaping a one-dimensional array into a two-dimensional array with one column, the tuple would be the shape of the array as the first dimension (data.shape) and 1 for the second dimension.

Putting this all together, we get the following worked example.

Running the example prints the shape of the one-dimensional array, reshapes the array to have 5 rows with 1 column, then prints this new shape.

### Reshape 2D to 3D Array

It is common to need to reshape two-dimensional data where each row represents a sequence into a three-dimensional array for algorithms that expect multiple samples of one or more time steps and one or more features.

A good example is the LSTM recurrent neural network model in the Keras deep learning library.

The reshape function can be used directly, specifying the new dimensionality. This is clear with an example where each sequence has multiple time steps with one observation (feature) at each time step.

We can use the sizes in the shape attribute on the array to specify the number of samples (rows) and columns (time steps) and fix the number of features at 1.

Putting this all together, we get the following worked example.

Running the example first prints the size of each dimension in the 2D array, reshapes the array, then summarizes the shape of the new 3D array.

This section provides more resources on the topic if you are looking go deeper.

## Summary

In this tutorial, you discovered how to access and reshape data in NumPy arrays with Python.

Specifically, you learned:

• How to convert your list data to NumPy arrays.
• How to access data using Pythonic indexing and slicing.
• How to resize your data to meet the expectations of some machine learning APIs.

Do you have any questions?

## Get a Handle on Linear Algebra for Machine Learning! #### Develop a working understand of linear algebra

...by writing lines of code in python

Discover how in my new Ebook:
Linear Algebra for Machine Learning

It provides self-study tutorials on topics like:
Vector Norms, Matrix Multiplication, Tensors, Eigendecomposition, SVD, PCA and much more...

### 70 Responses to How to Index, Slice and Reshape NumPy Arrays for Machine Learning

1. ltshan October 27, 2017 at 12:58 pm #

Great articles. Still get much base knowledge though used python for a while.

• Jason Brownlee October 27, 2017 at 2:57 pm #

2. Ben January 8, 2018 at 7:53 pm #

I have a clarification regarding converting single dimensional array to matrix form(2D). Why we have to convert 1D to 2D in machine learning?

• Jason Brownlee January 9, 2018 at 5:27 am #

Most machine learning algorithms expect a matrix as input, each row is one observation.

3. Anthony The Koala March 24, 2018 at 8:53 am #

Dear Dr Jason, :,
Thank you for providing this tutorial on slicing. It will certainly help me understand material on LSTMs on your page, and your e-books.

My question is on 2-D slicing and the method of slicing. I would like a “generalised” concept of slicing.
In 1-D slicing an array can be split as:
myarray[from:to] – that is understood

In 2-D slicing, “Split Input and Output Features”, you gave two examples of splitting
x = [ : , :-1]
y = [ : , -1]

I would like clarification please in the context of myarray[from:to] especially for 2D splicing especially where there are two colons ‘:’

myarray[from: to] and x [ : , : -1] For x, to = : , and from = : – 1,

Thank you,
Anthony of NSW

• Jason Brownlee March 25, 2018 at 6:24 am #

Good question Anthony!

When you just provide an index instead of a slice, like -1, it will select only that column/row, in this case the last column.

Doers that help?

4. Ashish K S Arya April 27, 2018 at 5:53 pm #

Hello;
thanks for such nice tutorial, i am new to numpy. While I am working on deep learning algorithms at a certain juncture in my program I need to create an array of (1000,256,256,3) dims where 1000 images data (of size 256*256*3) can be loaded.

Can you kindly help me in doing this in Python.

code looks like the following:

x_train=np.empty([256,256,3])

for i in range(0,1000):

pic= Image.open(f'{path}%s.jpg’ %i)

pic=pic.resize([256,256])

x_train2= np.asarray(pic)

x_train=np.stack((x_train,x_train2))

print(x_train.shape)

Thanks

• Jason Brownlee April 28, 2018 at 5:25 am #

A good trick is to load the data into a list, convert the list to an array, and then reshape the array to the required dimensionality.

5. Fatemeh June 8, 2018 at 6:01 am #

Great. the best description I had seen.

• Jason Brownlee June 8, 2018 at 6:18 am #

6. Visalini August 25, 2018 at 4:37 pm #

Hi Jason,
How to convert a 3D array into 1D array..

• Jason Brownlee August 26, 2018 at 6:23 am #

X = X.reshape((X.shape, X.shappe, 1))

7. SkrewEverything August 25, 2018 at 5:34 pm #

We can access 2D array just like C: data.

Using data[0, 0] is not the only way like you said.

Which version of python are you using?

• Jason Brownlee August 26, 2018 at 6:24 am #

Using [i, j] is valid for 2d numpy array access in Python 2 and 3.

8. ai October 1, 2018 at 3:58 am #

I’ve been searching for this information for so long. Thank you so so so much sir

• Jason Brownlee October 1, 2018 at 6:30 am #

You’re welcome!

9. Haotian Wang October 8, 2018 at 5:52 am #

Jason, you help me a lot

• Jason Brownlee October 8, 2018 at 9:29 am #

I’m happy to hear that it helped.

10. Maijama'a October 27, 2018 at 9:37 pm #

Thank you so much for this clear tutorial.

• Jason Brownlee October 28, 2018 at 6:10 am #

11. RasmusT January 29, 2019 at 6:42 am #

Hi, I am dealing with normalization of 3d timeseries data.

I have 3d time series data (samples, features, timestemps).

How am I supposed to reshape my 3d data to do normalization?
I am quessing it goes like this:
From [samples, features, timesteps] to ([timesteps,features] or [features,timesteps]) and then use like MinMaxScaler to fit_transform on the training data and then transform on test data?

• Jason Brownlee January 29, 2019 at 11:39 am #

It is a good idea to normalize per time series across all samples.

12. Mansoor February 4, 2019 at 7:13 pm #

Thank you very much for this very useful, very easy to follow and understand introduction to NumPy arrays. It was very helpful.

• Jason Brownlee February 5, 2019 at 8:14 am #

13. Kuruvilla Abraham February 8, 2019 at 2:24 pm #

Hi jason,

my Dataframe has non – image data of dimensions (1446736, 11).

How can i reshape this array to be fed into CNN model

• Jason Brownlee February 9, 2019 at 5:52 am #
• Kuruvilla Abraham February 9, 2019 at 4:41 pm #

thanks Jason will this apply to CNN model as well as this for LSTM ryt ?

• Jason Brownlee February 10, 2019 at 9:40 am #

Yes.

14. Eva April 9, 2019 at 8:00 pm #

Hi Jason, thanks for the tutorial, really helps strengthening the basics.
I have a somewhat related question – the numpy reshape function has a default reshape order C. When working in Keras, is there any difference in using the numpy reshape or the keras native reshape? Uses that one the same order? And if not, is it possible to use numpy native functions directly in Keras code?

Thanks! 🙂

• Jason Brownlee April 10, 2019 at 6:11 am #

They solve different things.

You can use numpy to reshape your arrays.

Keras offers a reshape layer, to reshape tensors as part of a neural net.

15. Rahul April 13, 2019 at 5:37 pm #

You’re awesome dude! So well explained. Thank you!

• Jason Brownlee April 14, 2019 at 5:44 am #

16. Nastaran April 26, 2019 at 11:26 am #

Hi,

Just wondering how I can import a dataset of 2D arrays ?

Thanks

• Jason Brownlee April 26, 2019 at 1:57 pm #

Do you mean load from file?

17. dong zhan May 27, 2019 at 12:32 pm #

very thoughtful of you to give this tutorial, otherwise, it would be much harder for me to follow your machine learning tutorial, thank you so much

• Jason Brownlee May 27, 2019 at 2:38 pm #

18. Sandeep Dawre June 5, 2019 at 7:51 pm #

One of the best article!!

• Jason Brownlee June 6, 2019 at 6:22 am #

Thanks!

19. Hemanth June 18, 2019 at 4:24 am #

• Jason Brownlee June 18, 2019 at 6:42 am #

You’re welcome.

20. Rodrigue KANKEU July 2, 2019 at 5:21 pm #

Hi Jason thanks a lot for this nice tutorial again. I have a problem with the following sentence of the section 4 about reshaping.
For example, some libraries, such as scikit-learn, may require that a one-dimensional array of output variables (y) be shaped as a two-dimensional array with one column and outcomes for each column.

I’m not getting well Isn’t?
For example, some libraries, such as scikit-learn, may require that a one-dimensional array of output variables (y) be shaped as a two-dimensional array with one column and outcomes for each “row”.
In fact I’m confused.
Thanks a lot for the work done.

• Jason Brownlee July 3, 2019 at 8:24 am #

Yes, I mean row. Updated.

Yes, so [1, 2, 3] is a 1D with the shape (3,) becomes [[1, 2, 3]] or one column with 3 rows shape (1,3).

21. Rakesh July 24, 2019 at 2:57 pm #

Dear sir, I want to input my tfidf vector of shape 156060×15103 into LSTM layer with 150 timeseries step and 15103 features .. my lstm input should look something like

If array reshaping does not help here, please suggest any alternative way of how to create lstm layer with (None, 150, 15103) using tfidf input.
My aim is to use tfidf output as input to LSTM layer with 150 timesteps.

• Jason Brownlee July 25, 2019 at 7:39 am #

Set the input_shape argument on the first LSTM layer to the desired shape.

22. tina August 15, 2019 at 7:08 pm #

how to ask the user to input a 3d and to solve that input as an inverse

• Jason Brownlee August 16, 2019 at 7:50 am #

Sorry, I don’t follow. Can you elaborate?

23. Nick August 28, 2019 at 9:46 pm #

Hi Jason,

I am experiencing some weird indexing problem where I seemingly have the correct coordinates to call both `cv2.rectangle()` and `plt.Rectangle()` but then using the same coordintes for slicing does not work, ie. y1 and y2 need to be reversed. I have an issue up on OpenCV Github but can you take a look if you have a moment? https://github.com/opencv/opencv/issues/15406

• Jason Brownlee August 29, 2019 at 6:07 am #

Sorry to hear that, this sounds like an opencv issue, not an python array issue.

Good Luck.

24. Ipsita October 10, 2019 at 6:18 pm #

I have got a .dat file that contains the matrix images is of size 784-by-1990, i.e., there are totally 1990 images, and each column of the
matrix corresponds to one image of size 28-by-28 pixels.how to visualize it.Pls help.

• Jason Brownlee October 11, 2019 at 6:15 am #
25. Abdoo October 13, 2019 at 6:55 pm #

Great Article!

I have a data to be fed into stacked LSTM. The data of the shape (81,25,12). When I do predictions using model.predict, the output will of course be 3D again (81,25,12). But I want to plot each feature by itself. I want to convert the output back into 2D and slice each column/feature for error calculations and plotting.

How can I convert 3D back into to 2D array?
thank you so much Jason!

• Jason Brownlee October 14, 2019 at 8:06 am #

The output does not have to be 3d, the output can be any shape you design into your model.

Nevertheless, you can reshape an array using the reshape() function:

data = data.reshape((??))

26. Ryan October 16, 2019 at 3:58 am #

Hi Jason,

Can you explain an array slicing like [:,:,1] for a 2D array please?

• Jason Brownlee October 16, 2019 at 8:11 am #

Yes, it selects all rows and column 0.

27. shadrack kodondi October 17, 2019 at 1:37 am #

the best training in ML i have ever come across…THANK YOU

• Jason Brownlee October 17, 2019 at 6:39 am #

Thanks.

28. Anthony The Koala November 15, 2019 at 9:44 am #

Dear Dr Jason,

Where it says:
“For the input features, we can select all rows and columns except the last one by…”

To clarify:
“For the input features, we can select all rows and all columns except the last column by….”

Where it says:
“For the output column, we can select all rows again using “:
and index just the last column by….”

To clarify:
“For the output column, we can select all rows again using “:
and index just the last row by….”

Reason, in the last example, all columns are displayed of the last row.

Alternatively, only the last row is displayed.

Thank you,
Anthony of Sydney

• Anthony The Koala November 15, 2019 at 10:04 am #

Dear Dr Jason,
My further elaboration on section 2

#Select all rows and first two columns
doo[:,0:2]
array([[1, 2],
[4, 5],
[7, 8]])

The list is not exhaustible, but you get a better feel by experimenting.

Thank you,
Anthony of Sydney

• Anthony The Koala November 15, 2019 at 11:18 am #

Dear Dr Jason,
While the above methods look at selecting either ‘successive’ rows or columns, the finishing touch is to select particular columns or particular rows.

Still exploring the fundamentals of matrix selection,

How if you have a 3D matrix, how to slice a matrix.

Thank you
Anthony of Sydney

• Jason Brownlee November 16, 2019 at 7:17 am #

It is important to get good at slicing in Python.

• Jason Brownlee November 16, 2019 at 7:16 am #

Well done!

• Jason Brownlee November 16, 2019 at 7:16 am #

Thanks.

• Anthony The Koala November 20, 2019 at 1:33 am #

Dear Dr Jason,
I had a go at slicing a 3D array. I was able to select particular columns and particular rows. I don’t know if 3D arrays are sliced or if there is an application for slicing 3D arrays. So here it is.

I note that the slicing techniques are not exhaustible.

Whether you call this selection or slicing depends on whether you use indices or the slicing operator “:”.

Whatever procedure, the end result is that you want to get a subset of the original data structure.

What is the application of 3D slicing and/or selection?

Thank you
Anthony of Sydney

• Jason Brownlee November 20, 2019 at 6:19 am #

Nice work!

29. spankwire November 30, 2019 at 4:37 am #

In more advanced use case, you may find yourself needing to switch the dimensions of a certain matrix. This is often the case in machine learning applications where a certain model expects a certain shape for the inputs that is different from your dataset. NumPy’s

30. Iyanda Taofeek December 13, 2019 at 10:06 am #

Please how can I convert a 1D array to 7D array?

• Jason Brownlee December 13, 2019 at 1:42 pm #

You can use the reshape() function to specify the dimensions of existing numpy array.