Reshaping an array in python

               You have created an array. you want to reshape the array without altering data, this is method for you.

Here, built-in method reshape() is used in Numpy. Let us do this for 1D and 2D array.

Reshaping a 1D array into 2D array:

              This code starts from importing numpy and its object. A single dimensional array is created with elements.

The array is reshaped with 3 rows and 2 columns by the use of reshape() function.

Original array and reshaped array is printed as output.

Python Code:

import numpy as np1

# Create a 1D array with elements

s_arr = np1.array([11, 22, 33, 44, 55, 66])

# Let us Reshape into 3 rows and 2 columns

reshaped_arr = s_arr.reshape(3, 2)

print("Original array:", s_arr)

print("Reshaped array:\n", reshaped_arr)

Output:

This is the output for the above program

Original array: [11 22 33 44 55 66]

Reshaped array:

 [[11 22]

 [33 44]

 [55 66]]

Note: if you want to change row into column, use reshape(row value,-1).

Next one is 1D to 3D.

Reshaping a 1D array into 3D array:

              This program creates a single dimensional array. Reshape it into three Dimensional array. It uses Numpy for this purpose.

Python Code:

#imports the numpy object np1

import numpy as np1

# Create a 1D array with elements

s_arr = np1.array([11, 22, 33, 44, 55, 66, 77, 88, 99, 100])

# Let us Reshape

reshaped_arr =np1. arange(1, 10).reshape(3, 3)

#print the original array and reshaped array

print("Original array:", s_arr)

print("Reshaped array:\n", reshaped_arr)

Output:

The output is given below..

Original array: [ 11  22  33  44  55  66  77  88  99 100]

Reshaped array:

 [[1 2 3]

 [4 5 6]

 [7 8 9]]

That’s all. This blog post explains you about reshaping the array elements with altering the data in python. Hope, this is useful to you. Keep coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Datatypes and Variables in java script