In this post I will explain you how to manipulate a numpy array with python.

First import numpy and pyplot libraries.

import numpy as np
import matplotlib.pyplot as plt

Then let’s make an arbitrary numpy array. For example, let’s make an array of 25 elements.
a = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])

You can convert this array into a matrix. Let’s convert it into a  5 X 5 matrix. For that we use reshape command in python.
b = a.reshape(5,5)

We can select any part of the matrix, for example the 3rd column from the left can be selected as follows.
c = b[:,2]

From the selected part, we can do further manipulation of data. Look at the following where the sine value is taken for the selected column above.
d = np.sin(c)

Now lets Plot the c Vs d. The r- means that it is a red line.
plt.plot(c,d,’r-‘)

Now lets view the graph
plt.show()

#If you are interested in saving the selected content into a text file …..

My_File = open (“py_test.txt”,”wb”) # wb means that you open the file as writable

My_Content = c
My_File.write(bytes(My_Content))
My_File.close()

You can download the files from here.

Manipulation of Arrays in Python

Leave a Reply

Your email address will not be published. Required fields are marked *