Working With Arrays in NumPy

image.png

Image Source: EDUCBA

In NumPy, the main fundamental data structure to deal with computing is the array. The majority of data science and other computing task heavily relies on NumPy array. The array() function is used to create an array in NumPy. In the below example we will see a simple example of how to create one dimensional array from a list.

import numpy as np
num_list = [12, 45, 89, 34, 23, 9, 14, 44, 88, 67]

array_1 = np.array(num_list)

array_1

array_1.shape

type(array_1)

In the above code, shape is the attribute of array that returns a tuple showing the number of rows and columns. Since we have only one axis in our array, it returns (10,) indicating it has only one row. If we checked the type of our array, it will return ndarray, a term for array objects in NumPy. ndarray means N-Dimensional Array

image.png

In the same way, you can pass either a tuple or set instead of list to an array function to create an array. Remember, while creating an array from a set, it will eliminate any duplicate items in the set. Now lets see on creating a two dimensional array(2D). We can do this by passing a list within a list. A simple example is shown below:

num_list2 = [[0,0,0],[1,1,1],[2,2,2]]
array_2 = np.array(num_list2)
array_2

array_2.shape

If we run the above program, it will return the output as:

image.png

We can see the dimension of array is 3x3, which means it has 3 rows and 3 columns. Next we will see how to reshape an array. Reshaping the array means changing the shape(dimension) of the array without altering its data. In the above example of num_list that contains one row of 10 elements we will reshape that 1D array into 2D array of shape (5,2).

array_1_reshaped = np.array(num_list).reshape(5,2)
array_1_reshaped

array_1_reshaped.shape

If we run this program then we will see the following output:

image.png

So in this post, we saw a simple example of creating an array in NumPy and reshaping it. In the next tutorial, we will talk about indexing and slicing an array using NumPy methods.

Previous NumPy posts


Intro To NumPy Library



0
0
0.000
2 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support. 
 

0
0
0.000
avatar

python make it easy, i have seen a few coworkers working with this tech :D

0
0
0.000