- NumPy Array Reshaping
- Reshape From 1-D to 2-D
- Example
- Reshape From 1-D to 3-D
- Example
- Can We Reshape Into any Shape?
- Example
- Returns Copy or View?
- Example
- Unknown Dimension
- Example
- Flattening the arrays
- Example
- Convert 1d Array to 2d Array Python
- How to Convert 1d Array to 2d Array in Python?
- Syntax
- Example 1: Convert 1d Array to 2d Array in Python Using “reshape()” Method With “np.arange()” Method
- Example 2: Convert 1d Array to 2d Array in Python Using “np.reshape()” Method
- Conclusion
- About the author
- Maria Naz
- numpy.reshape#
- Convert 1D array to 2D array in Python (numpy.ndarray, list)
- Convert a one-dimensional numpy.ndarray to a two-dimensional numpy.ndarray
- Convert a one-dimensional list to a two-dimensional list
- With NumPy
- Without NumPy
- Related Categories
- Related Articles
NumPy Array Reshaping
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of elements in each dimension.
Reshape From 1-D to 2-D
Example
Convert the following 1-D array with 12 elements into a 2-D array.
The outermost dimension will have 4 arrays, each with 3 elements:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
Reshape From 1-D to 3-D
Example
Convert the following 1-D array with 12 elements into a 3-D array.
The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
Can We Reshape Into any Shape?
Yes, as long as the elements required for reshaping are equal in both shapes.
We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it into a 3 elements 3 rows 2D array as that would require 3×3 = 9 elements.
Example
Try converting 1D array with 8 elements to a 2D array with 3 elements in each dimension (will raise an error):
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
Returns Copy or View?
Example
Check if the returned array is a copy or a view:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
The example above returns the original array, so it is a view.
Unknown Dimension
You are allowed to have one «unknown» dimension.
Meaning that you do not have to specify an exact number for one of the dimensions in the reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.
Example
Convert 1D array with 8 elements to 3D array with 2×2 elements:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
Note: We can not pass -1 to more than one dimension.
Flattening the arrays
Flattening array means converting a multidimensional array into a 1D array.
We can use reshape(-1) to do this.
Example
Convert the array into a 1D array:
Note: There are a lot of functions for changing the shapes of arrays in numpy flatten , ravel and also for rearranging the elements rot90 , flip , fliplr , flipud etc. These fall under Intermediate to Advanced section of numpy.
Convert 1d Array to 2d Array Python
Like other programming languages, Python also contains several built-in data structures, for instance, arrays. Arrays can be one-dimensional, two-dimensional, or depending on the user’s requirements, provide a way to organize and save data. Additionally, you can use the built-in Python methods to retrieve or modify that data.
This post will illustrate the different methods for converting a 1d array into a 2d array.
How to Convert 1d Array to 2d Array in Python?
To perform the converting operation on a one-dimensional array to a two-dimensional array in Python, the “reshape()” function can be utilized that enables users to reshape an array. More specifically, reshaping is known as changing the shape of a given array which is determined by the number of elements in every dimension without changing its data.
Syntax
Utilize the below-stated syntax for the reshape() method:
Here, the “input_string” is the variable name that contains the value of the array, the “row” and “col” are two parameters that are passed to the “reshape” function.
Example 1: Convert 1d Array to 2d Array in Python Using “reshape()” Method With “np.arange()” Method
To convert a one-dimension array to a two-dimensional array, first import the Numpy library as np:
Now, create an array variable and initialize it with the term “original_array”. Then, assign a value by utilizing an “np.arange()” function:
Here, “arange()” is the function of the “np” library, and we have passed a value “8” as the function parameter.
Print the previously created array using the “print()” function:
Next, create a variable that will keep the converted array. Then, call the “reshape()” method by passing a desired number of rows and columns as an argument to associate this method with the specified variable:
Finally, print the converted array:
It can be seen that the specified one-dimensional array has been successfully converted to a two-dimensional array:
Example 2: Convert 1d Array to 2d Array in Python Using “np.reshape()” Method
Another way to convert the 1d array into the 2d array is to utilize the “np.reshape()” function. To do so, first, create a new 1d input array:
Now, call the “np.reshape()” method with a 1d input array by passing the parameters. Here, the “-1” refers to the size of the specified input array:
Print the resultant 2d array from the np.reshape() method:
That’s all about converting a 1d array into a 2d array in Python through different methods.
Conclusion
To convert a 1d array into a 2d array in Python, the “np.reshape()” method and “reshape()” method with the “np.arange()” method can be used. Both methods enable users to reshape the input array without modifying its data. This post illustrated the different methods for converting a 1d array into a 2d array.
About the author
Maria Naz
I hold a master’s degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.
numpy.reshape#
Gives a new shape to an array without changing its data.
Parameters : a array_like
newshape int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
order , optional
Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.
Returns : reshaped_array ndarray
This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.
It is not always possible to change the shape of an array without copying the data.
The order keyword gives the index ordering both for fetching the values from a, and then placing the values into the output array. For example, let’s say you have an array:
>>> a = np.arange(6).reshape((3, 2)) >>> a array([[0, 1], [2, 3], [4, 5]])
You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling.
>>> np.reshape(a, (2, 3)) # C-like index ordering array([[0, 1, 2], [3, 4, 5]]) >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape array([[0, 1, 2], [3, 4, 5]]) >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering array([[0, 4, 3], [2, 1, 5]]) >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F') array([[0, 4, 3], [2, 1, 5]])
>>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, 6) array([1, 2, 3, 4, 5, 6]) >>> np.reshape(a, 6, order='F') array([1, 4, 2, 5, 3, 6])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]])
Convert 1D array to 2D array in Python (numpy.ndarray, list)
This article explains how to convert a one-dimensional array to a two-dimensional array in Python, both for NumPy arrays ndarray and for built-in lists list .
See the following article on how to convert (= flatten) a multi-dimensional array to a one-dimensional array.
Convert a one-dimensional numpy.ndarray to a two-dimensional numpy.ndarray
Use the reshape() method to transform the shape of a NumPy array ndarray . Any shape transformation is possible. This includes but is not limited to transforming from a one-dimensional array to a two-dimensional array.
By using -1 , the size of the dimension is automatically calculated.
import numpy as np a = np.arange(6) print(a) # [0 1 2 3 4 5] print(a.reshape(2, 3)) # [[0 1 2] # [3 4 5]] print(a.reshape(-1, 3)) # [[0 1 2] # [3 4 5]] print(a.reshape(2, -1)) # [[0 1 2] # [3 4 5]]
If you specify a shape that does not match the total number of elements in the original array, an error will be raised.
# print(a.reshape(3, 4)) # ValueError: cannot reshape array of size 6 into shape (3,4) # print(a.reshape(-1, 4)) # ValueError: cannot reshape array of size 6 into shape (4)
Convert a one-dimensional list to a two-dimensional list
With NumPy
With NumPy, you can convert list into numpy.ndarray , transform the shape with reshape() , and then convert it back to list .
l = [0, 1, 2, 3, 4, 5] print(np.array(l).reshape(-1, 3).tolist()) # [[0, 1, 2], [3, 4, 5]] print(np.array(l).reshape(3, -1).tolist()) # [[0, 1], [2, 3], [4, 5]]
See the following article on how to convert numpy.ndarray and list to each other.
Without NumPy
If NumPy is not available, you can still achieve the transformation using list comprehensions, range() , and slices.
def convert_1d_to_2d(l, cols): return [l[i:i + cols] for i in range(0, len(l), cols)] l = [0, 1, 2, 3, 4, 5] print(convert_1d_to_2d(l, 2)) # [[0, 1], [2, 3], [4, 5]] print(convert_1d_to_2d(l, 3)) # [[0, 1, 2], [3, 4, 5]] print(convert_1d_to_2d(l, 4)) # [[0, 1, 2, 3], [4, 5]]
In the function above, the first argument is the original list, and the second argument is the number of elements in the inner list (i.e., the number of columns). If there is a remainder, a list with a different number of elements will be stored, as in the last example.
If you want to specify the number of rows:
def convert_1d_to_2d_rows(l, rows): return convert_1d_to_2d(l, len(l) // rows) print(convert_1d_to_2d_rows(l, 2)) # [[0, 1, 2], [3, 4, 5]] print(convert_1d_to_2d_rows(l, 3)) # [[0, 1], [2, 3], [4, 5]] print(convert_1d_to_2d_rows(l, 4)) # [[0], [1], [2], [3], [4], [5]]
The above function is a basic example. If the total number of elements is not divisible by the number of rows you specify, the actual number of rows in the result may differ from what you’ve specified, as shown in the last example.
Related Categories
Related Articles
- Difference between lists, arrays and numpy.ndarray in Python
- Convert numpy.ndarray and list to each other
- NumPy: Create an ndarray with all elements initialized with the same value
- How to flatten a list of lists in Python
- Sort a list, string, tuple in Python (sort, sorted)
- Pretty-print with pprint in Python
- Unpack and pass list, tuple, dict to function arguments in Python
- NumPy: Flip array (np.flip, flipud, fliplr)
- OpenCV, NumPy: Rotate and flip image
- Filter (extract/remove) items of a list with filter() in Python
- NumPy: Calculate cumulative sum and product (np.cumsum, np.cumprod)
- Get the number of items of a list in Python
- Image processing with Python, NumPy
- NumPy: Determine if ndarray is view or copy and if it shares memory
- Extract and replace elements that meet the conditions of a list of strings in Python