### NumPy Array Creation

Numpy provides many functions to create arrays. For Example:

``a = np.array([1, 2, 3, 4, 5, 6, 7])``

Note that the np.array() takes only one input parameter, that is a list of elements. If you want to create a multi-dimensional array, then pass tuples of numbers on the list. For example:

``b = np.array([(1,2,3), (4,5,6)])``

The type of the array can also be explicitly specified at creation time:

``c = np.array( [ [1,2], [3,4] ], dtype=complex )``

Apart from array method, we have some predefined functions that will generate a Numpy array, if the size of the array is known.

``````import numpy as np
a = np.zeros((2,2))   # Create an array of all zeros
print(a)              # Prints "[[ 0.  0.]
#         [ 0.  0.]]"

b = np.ones((1,2))    # Create an array of all ones
print(b)              # Prints "[[ 1.  1.]]"

c = np.full((2,2), 7) # Create a constant array
print(c)              # Prints "[[ 7.  7.]
#         [ 7.  7.]]"

d = np.eye(2)         # Create a 2x2 identity matrix
print(d)              # Prints "[[ 1.  0.]
#         [ 0.  1.]]"

e = np.random.random((2,2))  # Create an array filled with random values
print(e)``````

To create sequences of numbers, NumPy provides a function analogous to the range that returns arrays instead of lists. It is arange() method.
Syntax:
`numpy.arange(start, stop, step, dtype)`

``````import numpy as np
x = np.arange(5)
print(x) #[0  1  2  3  4] ``````

There is another function called linespace().This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified
Syntax:
`numpy.linspace(start, stop, num, endpoint, retstep, dtype)`

``````import numpy as np
x = np.linspace(10,20,5)
print(x) #[10.   12.5   15.   17.5  20.]``````

### Numpy array from existing data

numpy.asarray
This function is useful for converting Python sequence into ndarray. Given below is the proper format to write asarray.
Syntax:
`numpy.asarray(a, dtype = None, order = None)`
Lets learn more about the parameters, a is input data or sequence in any form such as list, list of tuples, tuples, tuple of tuples or tuple of lists. Then dtype is useful to specify the data type of the final ndarray but by default, the data type of input data is applied to the resultant ndarray. Order parameter has 2 values C (row major) or F (column major), C is the default.

Example:

``````# convert list to ndarray
import numpy as np
x = [1,2,3]
a = np.asarray(x)
print(a) ``````

### Array Operations

Arithmetic Operations
We can perform basic arithmetic operations on any two numpy arrays. Basic operations like addition, subtraction, multiplication and division can be done using both +, -, *, / symbols or add(), subtract(), multiply(), divide() methods. We can also find the square root of each element in numpy array by using sqrt() function.

``````import numpy as np
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum; both produce the array
# [[ 6.0  8.0]
#  [10.0 12.0]]
print(x + y)
print(np.add(x, y))

# Elementwise difference; both produce the array
# [[-4.0 -4.0]
#  [-4.0 -4.0]]
print(x - y)
print(np.subtract(x, y))

# Elementwise product; both produce the array
# [[ 5.0 12.0]
#  [21.0 32.0]]
print(x * y)
print(np.multiply(x, y))

# Elementwise division; both produce the array
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]
print(x / y)
print(np.divide(x, y))

# Elementwise square root; produces the array
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]
print(np.sqrt(x)) ``````

### Matrix Operations

n-dimension array can be treated as n-order matrix. We can perform matrix operations on these numpy array matrix such as calculating dot product, transpose of a matrix, etc.

``````import numpy as np
v = np.array([9,10])
w = np.array([11, 12])

# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))

x = np.array([[1,2], [3,4]])
print(x)    # Prints "[[1 2]
#          [3 4]]"
print(x.T)  # Prints "[[1 3]
#          [2 4]]" ``````

We can also calculate the sum of an entire row or column in a numpy array matrix by using sum() function and specifying the axis along which sum has to be computed. Similarly using min() we can calculate minimum value in each row or column

``````import numpy as np

x = np.array([[1,2],[3,4]])

print(np.sum(x))  # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0))  # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1))  # Compute sum of each row; prints "[3 7]"
print(np.min(axis=1))     # Compute min of each row ``````

Complete list of mathematical functions that can be performed on numpy arrays
https://docs.scipy.org/doc/numpy/reference/routines.math.html

Here are the links to tutorials to get started with basics of Python.

Python Lists and its in-built functions

Top 20 Programming Terms that Everyone should know

Conditional Statements in Python (if, elif, else)

Learn about Classes and Objects in Python

Follow me

### Akarsh Singh

Founder, Code in Python. Web and Android App Developer. He loves Python and wants to share his knowledge via this website. Follow him on Facebook, Twitter and Github.
Follow me

## 3 Comments

1. First of all I want to say superb blog! I had a quick question in which I’d like to ask if you don’t mind.
I was interested to find out how you center yourself and clear your head before writing.

I’ve had a tough time clearing my thoughts in getting my thoughts
out. I do enjoy writing but it just seems like the first 10
to 15 minutes are usually wasted simply just trying to figure out how to
begin. Any recommendations or tips? Cheers!

2. Hi, Neat post. There is a problem with your site in web explorer, may check this?
IE still is the marketplace leader and a large component
of folks will omit your fantastic writing because of this problem.

3. It’s going to be finish of mine day, except before finish I am reading this impressive post to improve my know-how.

© 2019 Code in Python