Sie sind auf Seite 1von 14

What is Numpy?

NumPy – Numerical Python is a library for the Python programming language, adding
support for large, multi-dimensional arrays and matrices, along with a large collection
of high-level mathematical functions to operate on these arrays.

How to install?
pip install numpy

1D and 2D Array

1D Array 2D Array
It is a single dimensional array i.e., many It is a two dimensional array
elements.
The first element is stored at index 0, second
at index 1 and so on.

Create Array Create Array


>>> import numpy as np >>> import numpy as np
>>> a = np.array([5,12,9,15,10]) >>> a = np.array([[4,12,34],[23,11,10]])
>>> print(a) >>> print(a)
[ 5 12 9 15 10] [[ 4 12 34]
[23 11 10]]

Print specific index value Print specific index value


>>> print(a[0],a[2],a[4]) >>> print(a[0][2],a[1][1], a[1][0])
5 9 10 34 11 23
Or
print(a[0, 2, 4])

Display number of elements Display rows and columns


>>> print(a.shape) >>> print(a.shape)
(5,) (2, 3)

Display dimension Display dimension


print(a.ndim) print(a.ndim)

Display Number of elements Display Number of elements


print(a.size) print(a.size)

Display size of each element Display size of each element


print(a.itemsize) print(a.itemsize)

Display data type Display data types


>>> print(type(a)) >>> print(type(a))
<class 'numpy.ndarray'> <class 'numpy.ndarray'>

Update Update
A[2] = 100 >>> a[1][1]=100
>>> print(a) >>> print(a)
[ 5 12 100 15 10] [[ 4 12 34]
[ 23 100 10]]
Append data
A1 = np.append(A, 23)
print(A1)
[5 12 100 15 10 23]
It adds only one data.

Create array with any values Create array with any values
>>> p = np.empty(5) >>> a = np.empty([2,2])
>>> print(p) >>> print(a)
[0.00000000e+000 0.00000000e+000 [[0.4375 2. ]
0.00000000e+000 4.94065646e-321 [1.09090909 0.75 ]]

Create array with zero Create array with zero


>>> p = np.zeros(5) >>> a = np.zeros([2,2])
>>> print(p) >>> print(a)
[0. 0. 0. 0. 0.] [[0. 0.]
[0. 0.]]

Create array with zero and int data type Create array with zero and int data type
>>> p = np.zeros(5,dtype = int) >>> a = np.zeros([2,2],dtype = int)
>>> print(p) >>> print(a)
[0 0 0 0 0] [[0 0]
[0 0]]

Create array with ones Create array with ones


>>> p = np.ones(5) >>> a = np.ones([2,2])
>>> print(p) >>> print(a)
[1. 1. 1. 1. 1.] [[1. 1.]
[1. 1.]]

Create array with 5 locations and value 8 Create array 2,2 with value 8
>>> p = np.full(5,8)
>>> print(p) >>> a = np.full([2,2],8)
[8 8 8 8 8] >>> print(a)
[[8 8]
[8 8]]

Create array with random function Create array with random function
>>> p = np.random.random(5) >>> a = np.random.random([2,2])
>>> print(p) >>> print(a)
[0.83377529 0.87501571 0.06585723 [[0.30769708 0.06059771]
0.30474124 0.11060145] [0.5178735 0.1086263 ]]

Create array with values 0 to 4 Creation of 2D with 1D


>>> b = np.arange(5) >>> import numpy as np
>>> print(b) >>> a = np.array([1,2,3,4,5,6])
[0 1 2 3 4] >>> b = np.reshape(a,(2,3))
>>> print(b)
Create array with value starting with 5, [[1 2 3]
ending at 19 and incremented by 3 [4 5 6]]
>>> b = np.arange(5,20,3)
>>> print(b)
[ 5 8 11 14 17]

>>> b = np.reshape(a,(3,2))
>>> print(b)
[[1 2]
[3 4]
[5 6]]
Transpose – rows to columns
>>>C = np.transpose(b)
>>>print(c)

array([[1, 3, 5],
[2, 4, 6]])

Creation of 1D from 2D
>>>D = C.flatten()
>>>print(D)

Copy() array([1, 3, 5, 2, 4, 6])


>>> import numpy as np
>>> x = np.array([10,15,20])
>>> y = x
>>> z = np.copy(x)
>>> x[0] = 5
>>> print(x)
[ 5 15 20]
>>> print(y)
[ 5 15 20]
>>> print(z)
[10 15 20]

Here, changes in X implemented to y but not


to Z.

Concatenate Concatenate
>>> import numpy as np >>> import numpy as np
>>> a = np.array([10,15,20]) >>> a = np.array([[1,2],[3,4]])
>>> b = np.array([12,14]) >>> print(a)
>>> c = np.concatenate([a,b,a]) [[1 2]
>>> print(c) [3 4]]
[10 15 20 12 14 10 15 20]
Concatenate row-wise
>>> b = np.concatenate([a,a])
>>> print(b)
[[1 2]
[3 4]
[1 2]
[3 4]]
By default, it concatenates row-wise.
Concatenate column-wise
>>> b = np.concatenate([a,a],axis = 1)
>>> print(b)
[[1 2 1 2]
[3 4 3 4]]

Vertical Stack
>>> c = np.array([100,100])
>>> print(np.vstack([a,c]))
[[ 1 2]
[ 3 4]
[100 100]]

Horizontal Stack
>>> d = np.array([[50],[50]])
>>> print(np.hstack([a,d]))
[[ 1 2 50]
[ 3 4 50]]

Slicing Slicing
>>> import numpy as np
>>> a = np.array([12,10,20,15,8])
>>> print(a)
[12 10 20 15 8]
>>> print(a[:])
[12 10 20 15 8] >>> import numpy as np
>>> print(a[1:3]) >>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
[10 20]
>>> print(a[:2]) >>> print(a)
[12 10] [[ 1 2 3 4]
>>> print(a[-2:]) [ 5 6 7 8]
[15 8] [ 9 10 11 12]]

>>> print(a[:2,:3])
[[1 2 3]
[5 6 7]]

>>> print(a[:3,:2])
[[ 1 2]
[ 5 6]
[ 9 10]]
>>> print(a[:,0])
[1 5 9]

>>> print(a[0,:])
[1 2 3 4]

>>> print(a[:-1,:-1])
[[1 2 3]
[5 6 7]]

>>> print(a[::-1,::-1])
[[12 11 10 9]
[ 8 7 6 5]
[ 4 3 2 1]]

>>> print(a[::-1,:])
[[ 9 10 11 12]
[ 5 6 7 8]
[ 1 2 3 4]]

>>> print(a[:,::-1])
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]]

Arithmetic operations Arithmetic operations


>>> import numpy as np >>> import numpy as np
>>> x = np.array([7,10,12,15]) >>> a = np.array([[1,2,3],[4,5,6]])
>>> y = np.array([16,5,11,20]) >>> print(a)
>>> add = x+y [[1 2 3]
>>> sub = x - y [4 5 6]]
>>> mpy = x * y >>> b = np.array([5,6,7])
>>> div = x / y >>> add = np.add(a,b)
>>> print(add) >>> sub = np.subtract(a,b)
[23 15 23 35] >>> mpy = np.multiply(a,b)
>>> print(sub) >>> div = np.divide(a,b)
[-9 5 1 -5] >>> print(add)
>>> print(mpy) [[ 6 8 10]
[112 50 132 300] [ 9 11 13]]
>>> print(div) >>> print(sub)
[0.4375 2. 1.09090909 0.75 ] [[-4 -4 -4]
[-1 -1 -1]]
# add = np.add(x,y) >>> print(mpy)
# sub = np.subtract(x,y) [[ 5 12 21]
#mpy = np.multiply(x,y) [20 30 42]]
#div = np.divide(x,y) >>> print(div)
[[0.2 0.33333333 0.42857143]
[0.8 0.83333333 0.85714286]]

Find average value of two arrays


T = (x + y)/2
Avg = np.sum(T)/ np.size(T)
print(Avg)

Arithmetic Operations (Scalar) Arithmetic operations (Scalar)


np.add(x, 1) >>> import numpy as np
Add 1 to each array element >>> a = np.array([[1,2,3],[4,5,6]])
np.subtract(x, 2) >>> print(a)
Subtract 2 from each element [[1 2 3]
np.multiply(x, 3) [4 5 6]]
Multiply each element by 3 >>> print(np.add(a,2))
np.divide(x, 4) [[3 4 5]
Divide each element by 4 and returns np.nan [6 7 8]]
for division by zero >>> print(np.subtract(a,2))
np.power(x, 5) [[-1 0 1]
Raise each element to 5th power [ 2 3 4]]
>>> print(np.multiply(a,2))
[[ 2 4 6]
[ 8 10 12]]
>>> print(np.divide(a,2))
[[0.5 1. 1.5]
[2. 2.5 3. ]]
>>> print(np.power(a,2))
[[ 1 4 9]
[ 6 25 36]]

Numpy Statistical operations Numpy Statistical operations


>>> a = np.array([1,2,3,4,5,6]) >>> a = np.array([[23,12,15],[10,34,45]])
>>> a
array([[23, 12, 15],
[10, 34, 45]])
>>> a.mean() >>> a.mean()
3.5 23.166666666666668
>>> a.sum() >>> a.sum()
21 139
>>> a.min() >>> a.min()
1 10
>>> a.max() >>> a.max()
6 45
>>> a.var() >>> a.var()
2.9166666666666665 159.80555555555554

Numpy – Basic Mathematical Functions Numpy – Basic Mathematical Functions

import numpy as np >>> import numpy as np


A = np.array([10.91, -9.46, 8.62, -10.19]) >>> a = np.array([[1.333,-2.542],[3.843,-4.45]])
print (np.abs(A)) >>> a
print (np.ceil(A)) array([[ 1.333, -2.542],
print(np.floor(A)) [ 3.843, -4.45 ]])
print(np.round(A)) >>> np.ceil(a)
array([[ 2., -2.],
array([10.91, 9.46, 8.62, 10.19]) [ 4., -4.]])
array([ 11., -9., 9., -10.]) >>> np.floor(a)
array([ 10., -10., 8., -11.]) array([[ 1., -3.],
array([ 11., -9., 9., -10.]) [ 3., -5.]])
>>> np.round(a)
array([[ 1., -3.],
[ 4., -4.]])

NumPy – Broadcasting
The term broadcasting refers to the ability of NumPy to treat arrays of different shapes
during arithmetic operations.
 If two arrays are of exactly the same shape, arithmetic operations are usually
done on corresponding elements.
 If two arrays are of different dimensions, the smaller array is broadcast to the
size of the larger array so that they have compatible shapes and arithmetic
operations are done on corresponding elements.

Numpy operations are usually done element-by-element which requires two arrays to have
exactly the same shape:

>>> import numpy as np


>>> a = np.array([1,2,3])
>>> b = np.array([4,5,6])
>>> a*b
array([ 4, 10, 18])

Array broadcasting in numpy

Example 1

The simplest broadcasting example occurs when an array and a scalar value are combined
in an operation:

>>> import numpy as np


>>> a = np.array([1,2,3])
>>> b = 2
>>> a*b
array([2, 4, 6])

The scalar b being stretched during the arithmetic operation into an array with the same
shape as a.

Example 2

It adds a one-dimensional array to a two-dimensional array provided number of elements in


1D is equivalent to number of columns in a row.

>>> import numpy as np


>>> a = np.array([[0,0,0],[10,10,10],[20,20,20],[30,30,30]])
>>> b = np.array([0,1,2])
>>> a
array([[ 0, 0, 0],
[10, 10, 10],
[20, 20, 20],
[30, 30, 30]])
>>> b
array([0, 1, 2])
>>> a+b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
The following figure demonstrates how array b is broadcast to become
compatible with a.

Example 3

When the trailing dimensions of the arrays are unequal, broadcasting fails because it is
impossible to align the values in the rows of the 1st array with the elements of the 2nd arrays
for element-by-element addition.

>>> import numpy as np


>>> a = np.array([[0,0,0],[10,10,10],[20,20,20],[30,30,30]])
>>> b = np.array([0,1,2,3])
>>> a+b
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
a+b
ValueError: operands could not be broadcast together with shapes (4,3) (4,)

Example 4

In some cases, broadcasting stretches both arrays to form an output array larger than either
of the initial arrays.
>>> import numpy as np
>>> a = np.array([[0],[10],[20],[3]])
>>> b = np.array([0,1,2])
>>> a
array([[ 0],
[10],
[20],
[ 3]])
>>> b
array([0, 1, 2])
>>> a+b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[ 3, 4, 5]])

The figure illustrates the stretching of both arrays to produce the desired 4x3 output array.

Covariance, correlation and linear regression


Co-variance
Covariance is a statistical measure that shows whether two variables are related by
measuring how the variables change in relation to each other.
>>> import numpy as np
>>> a = np.array([[0,3,4],[1, 2,4],[3, 4, 5]])
>>> b = np.cov(a)
>>> a
array([[0, 3, 4],
[1, 2, 4],
[3, 4, 5]])
>>> b
array([[4.33333333, 2.83333333, 2. ],
[2.83333333, 2.33333333, 1.5 ],
[2. , 1.5 , 1. ]])
Correlation
Correlation is the scaled measure of covariance. Besides, it is dimensionless. In other
words, the correlation coefficient is always a pure value and not measured in any units.
Formula

Cov(X,Y) – the covariance between the variables X and Y


σX – the standard deviation of the X-variable
σY – the standard deviation of the Y-variable
>>> import numpy as np
>>> a = np.array([100,200,300])
>>> b = np.array([50,60,70])
>>> print(np.corrcoef(a,b))
[[1. 1.]
[1. 1.]]

2 D ARRAY Linear Regression


Linear regression is a method used to find a relationship between a dependent variable
and independent variable(s).
Types
1. Simple Linear Regression: There is only one independent variable in it. E.g. the
price of the house depend only one field that is the size of the plot.
2. Multiple Linear Regression: There is more independent variable in it. E.g. the price
of the house depend one field that is the size of the plot and number of rooms.

Linear Equation: Y=aX + b


a: Slope of the line
b: Constant (Y-intercept, where X=0)
X: Independent variable
Y: Dependent variable
import numpy as np
import matplotlib.pyplot as plt
def estcoefficients(x,y):
n = np.size(x)
meanx, meany = np.mean(x), np.mean(y)
sy = np.sum(y*x - n*meany*meanx)
sx = np.sum(x*x - n*meanx*meanx)
a=sx/sy
b=meany-a*meanx
return(b,a)
def plotregline(x,y,b):
plt.scatter(x,y,color="r",marker="o",s=30)
ypred=b[0]+b[1]*x
plt.plot(x,ypred,color="g")
plt.xlabel('SIZE')
plt.ylabel('COST')
plt.show()
x=np.array([10,20,30,40,50]) # independent variable
y=np.array([400,800,1100,1700,2100]) # dependent variable
b=estcoefficients(x,y)
plotregline(x,y,b)

Array subset
import pandas as pd
import numpy as np
def sub_lists(list1):
# store all the sublists
sublist = [[]]
# first loop
for i in range(len(list1) + 1):
# second loop
for j in range(i + 1, len(list1) + 1):
# slice the subarray
sub = list1[i:j]
sublist.append(sub)
return sublist
x = np.array([1, 2, 3])
# driver code
print(sub_lists(x))

Das könnte Ihnen auch gefallen