Sie sind auf Seite 1von 32

1/8/2020 NUMPY - Jupyter Notebook

Numpy
--> Numpy is a core library for scientific computing in python

--> It provides a High - performance multidimensional array object and tools for working these Arrays.

# Creating a Numpy array


In [ ]:

# 1D Array

import numpy as np
a = np.array([1,2,3])
a

In [5]:

# 2D Array

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
a

Out[5]:

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

# Numpy v/s List


Advantages of Numpy over List

1. Less Memory
2. Fast
3. Convinient

localhost:8888/notebooks/NUMPY .ipynb 1/32


1/8/2020 NUMPY - Jupyter Notebook

In [6]:

# Example 1

import numpy as np
import time
import sys
#for list
S = range(1000)
print(sys.getsizeof(5)*len(S))
#for Numpy
D = np.arange(1000)
print(D.size*D.itemsize)

28000
4000

So, Memory occupied by List more than Numpy array.

In [8]:

import numpy as np
import time
import sys
SIZE = 1000000
L1 = range(SIZE)
L2 = range(SIZE)
A1 = np.arange(SIZE)
A2 = np.arange(SIZE)

# For List
start = time.time()
result = [(x,y) for x,y in zip(L1,L2)]
print((time.time()-start)*1000)

# For Numpy
start = time.time()
result = A1+A2
print((time.time()-start)*1000)

172.74856567382812
78.11713218688965

# Numpy Operations
1. Find the Dimension of the array
2. Find the bytesize of an array
3. Find the datatype of the elements

localhost:8888/notebooks/NUMPY .ipynb 2/32


1/8/2020 NUMPY - Jupyter Notebook

In [9]:

# Dimension of an Array

import numpy as np
a = np.array([1,2,3])
a.ndim

Out[9]:

In [10]:

import numpy as np
a = np.array([(1,2,3),(4,5,6),(7,8,9)])
a.ndim

Out[10]:

In [14]:

import numpy as np
a = np.array([1,2,3])
a.itemsize

Out[14]:

In [15]:

import numpy as np
a = np.array([1,2,3])
a.dtype

Out[15]:

dtype('int32')

In [20]:

# Size of an array

import numpy as np
a = np.array([1,2,3,4])
a.size

Out[20]:

localhost:8888/notebooks/NUMPY .ipynb 3/32


1/8/2020 NUMPY - Jupyter Notebook

In [22]:

# Shape of an Array

import numpy as np
a = np.array([(1,2,3,4,5),(6,7,8,9,10)])
a.shape

Out[22]:

(2, 5)

# Reshaping
In [120]:

import numpy as np
a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
a

Out[120]:

array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])

In [122]:

import numpy as np
a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
a.reshape(3,4)

Out[122]:

array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])

In [124]:

import numpy as np
a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
a.reshape(6,2)

Out[124]:

array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12]])

# Indexing

localhost:8888/notebooks/NUMPY .ipynb 4/32


1/8/2020 NUMPY - Jupyter Notebook

In [179]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
a[0]

Out[179]:

array([1, 2, 3])

In [180]:

a[1]

Out[180]:

array([4, 5, 6])

In [183]:

a[0,2]

Out[183]:

In [184]:

a[1,0:2]

Out[184]:

array([4, 5])

In [185]:

a[0:]

Out[185]:

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

In [186]:

a[:1]

Out[186]:

array([[1, 2, 3]])

In [188]:

a[0:,2]

Out[188]:

array([3, 6])

localhost:8888/notebooks/NUMPY .ipynb 5/32


1/8/2020 NUMPY - Jupyter Notebook

In [190]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
a[:1,2:] # :1 rows upto 1-1 i.e., 0 indexed row and 2: In that 0

Out[190]:

array([[3]])

# Slicing
In [28]:

import numpy as np
a = np.array([(1,2,3,4),(5,6,7,8)])
a[0,2]

Out[28]:

In [29]:

import numpy as np
a = np.array([(1,2,3,4),(5,6,7,8)])
a[0:,3]

Out[29]:

array([4, 8])

In [30]:

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

Out[30]:

array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])

In [31]:

import numpy as np
a = np.array([(1,2,3,4),(5,6,7,8),(9,10,11,12)])
a[0:2,3]

Out[31]:

array([4, 8])

localhost:8888/notebooks/NUMPY .ipynb 6/32


1/8/2020 NUMPY - Jupyter Notebook

In [35]:

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

Out[35]:

array([ 7, 11])

In [39]:

# linspace

import numpy as np
a = np.linspace(1,3,5) # It gives 5 values between 1 and 3
a

Out[39]:

array([1. , 1.5, 2. , 2.5, 3. ])

In [40]:

import numpy as np
a = np.linspace(1,5,10) # It gives 10 values between 1 and 5
a

Out[40]:

array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778,


3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])

# Min, Max, Sum and Mean


In [41]:

# Min

import numpy as np
a = np.array([1,2,3,4])
a.min()

Out[41]:

In [42]:

# Max

import numpy as np
a = np.array([1,2,3,4])
a.max()

Out[42]:

localhost:8888/notebooks/NUMPY .ipynb 7/32


1/8/2020 NUMPY - Jupyter Notebook

In [44]:

# Sum

import numpy as np
a = np.array([1,2,3,4])
a.sum()

Out[44]:

10

In [49]:

# Mean

import numpy as np
a = np.array([1,2,3,4])
a.mean()

Out[49]:

2.5

# Square Root
In [53]:

import numpy as np
a = np.array([1,2,3])
np.sqrt(a)

Out[53]:

array([1. , 1.41421356, 1.73205081])

# Variance
In [61]:

import numpy as np
a = np.array([1,2,3])
np.var(a) # OR a.var()

Out[61]:

0.6666666666666666

In [68]:

import numpy as np
a = np.array([1,2,3])
np.var(a,axis = 0) # axis = 0 for columns

Out[68]:

0.6666666666666666

localhost:8888/notebooks/NUMPY .ipynb 8/32


1/8/2020 NUMPY - Jupyter Notebook

In [69]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
np.var(a,axis = 0)

Out[69]:

array([2.25, 2.25, 2.25])

In [70]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
np.var(a,axis = 1)

Out[70]:

array([0.66666667, 0.66666667])

# Standard Deviation
In [72]:

import numpy as np
a = np.array([1,2,3])
np.std(a)

Out[72]:

0.816496580927726

In [73]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
np.std(a)

Out[73]:

1.707825127659933

# Mathematical Functions with Numpy


( + - * / )

localhost:8888/notebooks/NUMPY .ipynb 9/32


1/8/2020 NUMPY - Jupyter Notebook

In [155]:

# Addition

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
b = np.array([(1,2,3),(4,5,6)])
a+b

Out[155]:

array([[ 2, 4, 6],
[ 8, 10, 12]])

In [156]:

a*10

Out[156]:

array([[10, 20, 30],


[40, 50, 60]])

In [79]:

# Subtraction

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
b = np.array([(1,2,3),(4,5,6)])
a-b

Out[79]:

array([[0, 0, 0],
[0, 0, 0]])

In [80]:

# Multiplication

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
b = np.array([(1,2,3),(4,5,6)])
a*b

Out[80]:

array([[ 1, 4, 9],
[16, 25, 36]])

localhost:8888/notebooks/NUMPY .ipynb 10/32


1/8/2020 NUMPY - Jupyter Notebook

In [81]:

# Division

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
b = np.array([(1,2,3),(4,5,6)])
a/b

Out[81]:

array([[1., 1., 1.],


[1., 1., 1.]])

# Vertical and Horizontal Stacking


In [84]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
b = np.array([(1,2,3),(4,5,6)])
np.vstack((a,b))

Out[84]:

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

In [1]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
b = np.array([(1,2,3),(4,5,6)])
np.vstack(a)

Out[1]:

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

In [92]:

import numpy as np
a=np.array([(1,2,3),(4,5,6)])
b=np.array([(1,2,3),(4,5,6)])
np.hstack((a,b))

Out[92]:

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

localhost:8888/notebooks/NUMPY .ipynb 11/32


1/8/2020 NUMPY - Jupyter Notebook

In [94]:

import numpy as np
a=np.array([(1,2,3),(4,5,6)])
b=np.array([(1,2,3),(4,5,6)])
np.hstack(a)

Out[94]:

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

# To convert one Numpy array in single Horizontal Row is shown below :

In [96]:

import numpy as np
a=np.array([(1,2,3),(4,5,6)])
a.ravel()

Out[96]:

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

In [328]:

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

Out[328]:

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

localhost:8888/notebooks/NUMPY .ipynb 12/32


1/8/2020 NUMPY - Jupyter Notebook

In [329]:

#Ravel returns reference/view of original array whereas flatten returns copy of original ar
#the array you would notice that the value of original array also changes by using ravel.

import numpy as np
a = np.array([(1,2,3,4),(3,1,4,2)])

print ("Original array:\n ")


print(a)

# To check the dimension of array (dimension =2) ( and type is numpy.ndarray )


print ("Dimension of array-> " , (a.ndim))

print ("\nOutput for RAVEL \n")


# Convert nd array to 1D array
b = a.ravel()

# Ravel only passes a view of original array to array 'b'


print(b)
b[0]=1000
print(b)

# Note here that value of original array 'a' at also a[0][0] becomes 1000
print(a)

# Just to check the dimension i.e. 1 (and type is same numpy.ndarray )


print ("Dimension of array->" ,(b.ndim))

print("\nOutput for FLATTEN \n")

# Convert nd array to 1D array


c = a.flatten()

# Flatten passes copy of original array to 'c'


print(c)
c[0]=0
print(c)

# Note that by changing value of c there is no affect on value of original array 'a'
print(a)

print ("Dimension of array-> " , (c.ndim))

Original array:

[[1 2 3 4]
[3 1 4 2]]
Dimension of array-> 2

Output for RAVEL

[1 2 3 4 3 1 4 2]
[1000 2 3 4 3 1 4 2]
[[1000 2 3 4]
[ 3 1 4 2]]
Dimension of array-> 1

Output for FLATTEN

localhost:8888/notebooks/NUMPY .ipynb 13/32


1/8/2020 NUMPY - Jupyter Notebook

[1000 2 3 4 3 1 4 2]
[0 2 3 4 3 1 4 2]
[[1000 2 3 4]
[ 3 1 4 2]]
Dimension of array-> 1

# axis
'axis 0' for columns

'axis 1' for rows

In [162]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
a.sum(axis = 0) # columns will be added 1+4, 2+5, 3+6

Out[162]:

array([5, 7, 9])

In [164]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
a.sum(axis = 1) # Rows will be added 1+2+3, 4+5+6

Out[164]:

array([ 6, 15])

# Numpy Special Functions

localhost:8888/notebooks/NUMPY .ipynb 14/32


1/8/2020 NUMPY - Jupyter Notebook

In [108]:

# Sine Function

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1) # 0.1 for to get clear sinusoidal waveform, if we increa
y = np.sin(x)
plt.plot(x,y)
plt.title('Sine Function')
plt.show()

In [112]:

# Cosine Function

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1) # 0.1 for to get clear sinusoidal waveform, if we increa
y = np.cos(x)
plt.plot(x,y)
plt.title('Cosine Function')
plt.show()

localhost:8888/notebooks/NUMPY .ipynb 15/32


1/8/2020 NUMPY - Jupyter Notebook

In [165]:

# tan Function

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1) # 0.1 for to get clear sinusoidal waveform, if we increa
y=np.tan(x)
plt.plot(x,y)
plt.title('Tangential Function')
plt.show()

# eX (Exponential Function)
In [117]:

import numpy as np
a = np.array([1,2,3])
np.exp(a)

Out[117]:

array([ 2.71828183, 7.3890561 , 20.08553692])

In [3]:

import numpy as np
a = np.array([(1,2,3),(4,5,6)])
np.exp(a)

Out[3]:

array([[ 2.71828183, 7.3890561 , 20.08553692],


[ 54.59815003, 148.4131591 , 403.42879349]])

# log x ( Logarithmic Function )


localhost:8888/notebooks/NUMPY .ipynb 16/32
1/8/2020 NUMPY - Jupyter Notebook

In [131]:

# For log e

import numpy as np
a = np.array([1,2,3])
np.log(a)

Out[131]:

array([0. , 0.69314718, 1.09861229])

In [133]:

# For log10

import numpy as np
a = np.array([1,2,3])
np.log10(a)

Out[133]:

array([0. , 0.30103 , 0.47712125])

# Random Numbers
Random sampling (numpy.random)

Simple random data

rand(d0, d1, ..., dn) Random values in a given shape.


randn(d0, d1, ..., dn) Return a sample (or samples) from the “standard
normal” distribution.
randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high
(exclusive).
random_integers(low[, high, size]) Random integers of type np.int between low and high,
inclusive.
random_sample([size]) Return random floats in the half-open interval [0.0,
1.0).
random([size]) Return random floats in the half-open interval [0.0,
1.0).
ranf([size]) Return random floats in the half-open interval [0.0,
1.0).
sample([size]) Return random floats in the half-open interval [0.0,
1.0).
choice(a[, size, replace, p]) Generates a random sample from a given 1-D array
bytes(length) Return random bytes.

Permutations

shuffle(x) Modify a sequence in-place by shuffling its contents.


permutation(x) Randomly permute a sequence, or return a permuted range.

Distributions

beta(a, b[, size]) Draw samples from a Beta distribution.


binomial(n, p[, size]) Draw samples from a binomial distribution.
chisquare(df[, size]) Draw samples from a chi-square distribution.
dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution.
exponential([scale, size]) Draw samples from an exponential distribution.
localhost:8888/notebooks/NUMPY .ipynb 17/32
1/8/2020 NUMPY - Jupyter Notebook
exponential([scale, size]) Draw samples from an exponential distribution.
f(dfnum, dfden[, size]) Draw samples from an F distribution.
gamma(shape[, scale, size]) Draw samples from a Gamma distribution.
geometric(p[, size]) Draw samples from the geometric distribution.
gumbel([loc, scale, size]) Draw samples from a Gumbel distribution.
hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric
distribution.
laplace([loc, scale, size]) Draw samples from the Laplace or double exponential
distribution with specified location (or mean) and scale (decay).
logistic([loc, scale, size]) Draw samples from a logistic distribution.
lognormal([mean, sigma, size]) Draw samples from a log-normal distribution.
logseries(p[, size]) Draw samples from a logarithmic series distribution.
multinomial(n, pvals[, size]) Draw samples from a multinomial distribution.
multivariate_normal(mean, cov[, size, ...) Draw random samples from a multivariate
normal distribution.
negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution.
noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square
distribution.
noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F
distribution.
normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution.
pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified
shape.
poisson([lam, size]) Draw samples from a Poisson distribution.
power(a[, size]) Draws samples in [0, 1] from a power distribution with positive
exponent a - 1.
rayleigh([scale, size]) Draw samples from a Rayleigh distribution.
standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0.
standard_exponential([size]) Draw samples from the standard exponential distribution.
standard_gamma(shape[, size]) Draw samples from a standard Gamma distribution.
standard_normal([size]) Draw samples from a standard Normal distribution (mean=0,
stdev=1).
standard_t(df[, size]) Draw samples from a standard Student’s t distribution with df
degrees of freedom.
triangular(left, mode, right[, size]) Draw samples from the triangular distribution
over the interval [left, right].
uniform([low, high, size]) Draw samples from a uniform distribution.
vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution.
wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution.
weibull(a[, size]) Draw samples from a Weibull distribution.
zipf(a[, size]) Draw samples from a Zipf distribution.
Random generator
RandomState Container for the Mersenne Twister pseudo-random number generator.
seed([seed]) Seed the generator.
get_state() Return a tuple representing the internal state of the generator.
set_state(state) Set the internal state of the generator from a tuple.

In [138]:

import numpy as np
a = np.random.rand(10)
a

Out[138]:

array([0.52625294, 0.50381339, 0.93665492, 0.39962043, 0.65347305,


0.81619201, 0.46934638, 0.97348883, 0.16738441, 0.85027909])

localhost:8888/notebooks/NUMPY .ipynb 18/32


1/8/2020 NUMPY - Jupyter Notebook

In [140]:

import numpy as np
a = np.random.rand(2,10)
a

Out[140]:

array([[0.06038673, 0.9382885 , 0.06940907, 0.38874625, 0.68972089,


0.67557532, 0.93768864, 0.14875009, 0.44787986, 0.54621342],
[0.27047985, 0.77181386, 0.33941719, 0.74661391, 0.72929675,
0.68455709, 0.10662568, 0.54348001, 0.89725542, 0.27682081]])

In [148]:

import numpy as np
a = np.random.randn(10) # randn for Gaussian noise
a

Out[148]:

array([-1.04336777, -0.16241593, 1.45621524, 0.84100579, -0.19708338,


1.53644757, -1.16851494, 0.44448928, -0.32437719, -0.49714025])

# Using ones
In [152]:

import numpy as np
np.ones(5)

Out[152]:

array([1., 1., 1., 1., 1.])

In [157]:

import numpy as np
np.ones((10,2))

Out[157]:

array([[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.]])

localhost:8888/notebooks/NUMPY .ipynb 19/32


1/8/2020 NUMPY - Jupyter Notebook

In [288]:

a = np.array([[0],[2]]) # Values defines by the user


b = np.c_[np.ones((2,1)),a]
b

Out[288]:

array([[1., 0.],
[1., 2.]])

# Using np.c_
Translates slice objects to concatenation along the second axis.

In [173]:

import numpy as np
np.c_[np.array([1,2,3]), np.array([4,5,6])]

Out[173]:

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

In [175]:

import numpy as np
np.c_[np.array([[1,2,3]]), np.array([[4,5,6]])]

Out[175]:

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

In [176]:

import numpy as np
np.c_[np.array([[1,2,3]]),0, 0, np.array([[4,5,6]])]

Out[176]:

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

In [178]:

import numpy as np
np.c_[np.array([1,2,3,4]), np.array([5,6,7,8]), np.array([9,10,11,12])]

Out[178]:

array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])

# Boolean Indexing
localhost:8888/notebooks/NUMPY .ipynb 20/32
1/8/2020 NUMPY - Jupyter Notebook

Let’s consider an example where we have some data in an array and an array of names with duplicates. I’m
going to use here the randn function in numpy.random to generate some random normally distributed data

In [192]:

names = np.array(['Sai', 'Hari', 'Ravi','Sai', 'Ravi', 'Hari', 'Hari'])


names

Out[192]:

array(['Sai', 'Hari', 'Ravi', 'Sai', 'Ravi', 'Hari', 'Hari'], dtype='<U4')

In [195]:

names == 'Sai'

Out[195]:

array([ True, False, False, True, False, False, False])

In [196]:

names!='Hari'

Out[196]:

array([ True, False, True, True, True, False, False])

In [205]:

data = np.random.randn(7,4)
data

Out[205]:

array([[ 0.11921295, -0.03083315, -0.11629795, -0.81960809],


[ 0.49897673, 0.93282034, 1.60582703, -1.42885696],
[ 0.95505149, 2.16157806, 0.26706127, 0.02990409],
[ 1.22456513, 0.22667322, 0.09791234, -0.18027809],
[ 0.93496864, -0.08778793, 0.36962796, 0.16209075],
[ 0.73602414, -1.35146452, -0.8386976 , 1.75482532],
[ 1.12066197, 0.35001514, 0.32224715, -1.94568047]])

In [206]:

data[names == 'Ravi']

Out[206]:

array([[ 0.95505149, 2.16157806, 0.26706127, 0.02990409],


[ 0.93496864, -0.08778793, 0.36962796, 0.16209075]])

localhost:8888/notebooks/NUMPY .ipynb 21/32


1/8/2020 NUMPY - Jupyter Notebook

In [211]:

data1 = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12),(13,14,15),(16,17,18),(19,20,21)])
data1

Out[211]:

array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18],
[19, 20, 21]])

In [212]:

data1[names == 'Hari']

Out[212]:

array([[ 4, 5, 6],
[16, 17, 18],
[19, 20, 21]])

In [213]:

data1[names!='Ravi']

Out[213]:

array([[ 1, 2, 3],
[ 4, 5, 6],
[10, 11, 12],
[16, 17, 18],
[19, 20, 21]])

# Fancy Indexing
Fancy indexing is a term adopted by NumPy to describe indexing using integer arrays.

In [216]:

a = np.empty((8, 4))
a

Out[216]:

array([[ 0. , 0.29552021, 0.56464247, 0.78332691],


[ 0.93203909, 0.99749499, 0.97384763, 0.86320937],
[ 0.67546318, 0.42737988, 0.14112001, -0.15774569],
[-0.44252044, -0.68776616, -0.87157577, -0.97753012],
[-0.99616461, -0.92581468, -0.77276449, -0.55068554],
[-0.2794155 , 0.0168139 , 0.31154136, 0.57843976],
[ 0.79366786, 0.93799998, 0.99854335, 0.96988981],
[ 0.85459891, 0.66296923, 0.41211849, 0.12445442]])

localhost:8888/notebooks/NUMPY .ipynb 22/32


1/8/2020 NUMPY - Jupyter Notebook

In [219]:

a = np.empty((8, 4))
for i in range(8):
a[i] = i
a

Out[219]:

array([[0., 0., 0., 0.],


[1., 1., 1., 1.],
[2., 2., 2., 2.],
[3., 3., 3., 3.],
[4., 4., 4., 4.],
[5., 5., 5., 5.],
[6., 6., 6., 6.],
[7., 7., 7., 7.]])

In [221]:

a[[4, 3, 0, 6]]

Out[221]:

array([[4., 4., 4., 4.],


[3., 3., 3., 3.],
[0., 0., 0., 0.],
[6., 6., 6., 6.]])

In [222]:

a = np.arange(32)
a

Out[222]:

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, 25, 26, 27, 28, 29, 30, 31])

In [223]:

a = np.arange(32).reshape((8,4))
a

Out[223]:

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, 25, 26, 27],
[28, 29, 30, 31]])

localhost:8888/notebooks/NUMPY .ipynb 23/32


1/8/2020 NUMPY - Jupyter Notebook

In [226]:

a[[1, 5, 7, 2], [0, 3, 1, 2]] #This is also one type of slicing.

# From 1Row, 5Row, 7Row, 2Row take values of 0indexed, 3 indexed, 1 indexed, 2indexed value

Out[226]:

array([ 4, 23, 29, 10])

In [227]:

a[:, [0, 3, 1, 2]]

Out[227]:

array([[ 0, 3, 1, 2],
[ 4, 7, 5, 6],
[ 8, 11, 9, 10],
[12, 15, 13, 14],
[16, 19, 17, 18],
[20, 23, 21, 22],
[24, 27, 25, 26],
[28, 31, 29, 30]])

In [229]:

a[[1, 5, 7, 2]][:, [0, 3, 1, 2]] # Particular Row, All Columns with 0 3 1

Out[229]:

array([[ 4, 7, 5, 6],
[20, 23, 21, 22],
[28, 31, 29, 30],
[ 8, 11, 9, 10]])

# Transposing Arrays and Swapping Axes


Transposing is a special form of reshaping that similarly returns a view on the underlying data without copying
anything. Arrays have the transpose method and also the special T attribute

In [230]:

import numpy as np
a = np.arange(15).reshape((3, 5))
a

Out[230]:

array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])

localhost:8888/notebooks/NUMPY .ipynb 24/32


1/8/2020 NUMPY - Jupyter Notebook

In [233]:

a = np.arange(16).reshape(4,4)
a

Out[233]:

array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])

In [234]:

a = np.arange(16).reshape(2,2,2,2)
a

Out[234]:

array([[[[ 0, 1],
[ 2, 3]],

[[ 4, 5],
[ 6, 7]]],

[[[ 8, 9],
[10, 11]],

[[12, 13],
[14, 15]]]])

In [238]:

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

Out[238]:

array([[1, 2, 3]])

In [239]:

a.swapaxes(0,1)

Out[239]:

array([[1],
[2],
[3]])

In [242]:

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

Out[242]:

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

localhost:8888/notebooks/NUMPY .ipynb 25/32


1/8/2020 NUMPY - Jupyter Notebook

In [246]:

a.swapaxes(1,0) # 0,1 or 1,0 both are equal

Out[246]:

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

In [248]:

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

Out[248]:

array([[[0, 1],
[2, 3]],

[[4, 5],
[6, 7]]])

In [253]:

b.swapaxes(0,1)

Out[253]:

array([[[0, 1],
[4, 5]],

[[2, 3],
[6, 7]]])

In [252]:

b.swapaxes(0,2)

Out[252]:

array([[[0, 4],
[2, 6]],

[[1, 5],
[3, 7]]])

In [250]:

b.swapaxes(1,2)

Out[250]:

array([[[0, 2],
[1, 3]],

[[4, 6],
[5, 7]]])

localhost:8888/notebooks/NUMPY .ipynb 26/32


1/8/2020 NUMPY - Jupyter Notebook

In [269]:

a = np.arange(16).reshape(4,2,2)
a

Out[269]:

array([[[ 0, 1],
[ 2, 3]],

[[ 4, 5],
[ 6, 7]],

[[ 8, 9],
[10, 11]],

[[12, 13],
[14, 15]]])

In [270]:

a = np.arange(16).reshape(2,2,4)
a

Out[270]:

array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],

[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])

In [271]:

a.transpose(1,0,2)

Out[271]:

array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],

[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])

In [274]:

a.transpose(2,0,1)

Out[274]:

array([[[ 0, 4],
[ 8, 12]],

[[ 1, 5],
[ 9, 13]],

[[ 2, 6],
[10, 14]],

[[ 3, 7],
[11, 15]]])

localhost:8888/notebooks/NUMPY .ipynb 27/32


1/8/2020 NUMPY - Jupyter Notebook

In [275]:

x=np.arange(18).reshape(2,9)
x

Out[275]:

array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17]])

In [276]:

y=np.arange(18).reshape(9,2)
y

Out[276]:

array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[12, 13],
[14, 15],
[16, 17]])

In [285]:

a = [1,2,3,4]
print(a.append(5))

None

In [286]:

a.append(5)
a

Out[286]:

[1, 2, 3, 4, 5, 5]

# cumsum
In [290]:

a = np.array([1,2,3])
a.cumsum()

Out[290]:

array([1, 3, 6], dtype=int32)

localhost:8888/notebooks/NUMPY .ipynb 28/32


1/8/2020 NUMPY - Jupyter Notebook

In [291]:

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


a.cumsum()

Out[291]:

array([ 0, 1, 3, 6, 10, 15, 21, 28, 36], dtype=int32)

In [293]:

a.cumsum(axis = 0)

Out[293]:

array([[ 0, 1, 2],
[ 3, 5, 7],
[ 9, 12, 15]], dtype=int32)

In [295]:

a.cumsum(axis = 1)

Out[295]:

array([[ 0, 1, 3],
[ 3, 7, 12],
[ 6, 13, 21]], dtype=int32)

In [297]:

# cumprod

a.cumprod(axis = 0)

Out[297]:

array([[ 0, 1, 2],
[ 0, 4, 10],
[ 0, 28, 80]], dtype=int32)

In [299]:

a.cumprod(axis = 1)

Out[299]:

array([[ 0, 0, 0],
[ 3, 12, 60],
[ 6, 42, 336]], dtype=int32)

In [302]:

a = np.random.rand(2,5)
a

Out[302]:

array([[0.93311183, 0.87371724, 0.59164574, 0.43779468, 0.22540033],


[0.17032652, 0.93002699, 0.24043689, 0.2651052 , 0.40214078]])

localhost:8888/notebooks/NUMPY .ipynb 29/32


1/8/2020 NUMPY - Jupyter Notebook

In [305]:

a.sort()
a

Out[305]:

array([[0.22540033, 0.43779468, 0.59164574, 0.87371724, 0.93311183],


[0.17032652, 0.24043689, 0.2651052 , 0.40214078, 0.93002699]])

In [309]:

a.sort(1)
a

Out[309]:

array([[0.17032652, 0.24043689, 0.2651052 , 0.40214078, 0.93002699],


[0.22540033, 0.43779468, 0.59164574, 0.87371724, 0.93311183]])

In [312]:

a = np.array([[12,15],[10,1]])
a

Out[312]:

array([[12, 15],
[10, 1]])

In [320]:

np.argmin(a)

Out[320]:

In [321]:

np.argmax(a)

Out[321]:

In [322]:

b =np.array([[25,6,8],[5,6,9]])
b

Out[322]:

array([[25, 6, 8],
[ 5, 6, 9]])

localhost:8888/notebooks/NUMPY .ipynb 30/32


1/8/2020 NUMPY - Jupyter Notebook

In [323]:

np.argmin(b)

Out[323]:

In [324]:

np.argmax(b)

Out[324]:

In [314]:

a.sort(axis = 0)
a

Out[314]:

array([[10, 1],
[12, 15]])

In [315]:

a.sort(axis = 1)
a

Out[315]:

array([[ 1, 10],
[12, 15]])

In [316]:

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

Out[316]:

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

In [319]:

np.dot(x,np.ones(3))

Out[319]:

array([ 6., 15.])

localhost:8888/notebooks/NUMPY .ipynb 31/32


1/8/2020 NUMPY - Jupyter Notebook

In [326]:

from numpy.linalg import qr


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

Out[326]:

(array([[-0.24253563, -0.9701425 ],
[-0.9701425 , 0.24253563]]),
array([[-4.12310563, -5.33578375, -6.54846188],
[ 0. , -0.72760688, -1.45521375]]))

In [331]:

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


arr2 = np.array([[7,8,9], [10, 11, 12]])
np.concatenate([arr1,arr2])

Out[331]:

array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])

In [333]:

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


arr2 = np.array([[7,8,9], [10, 11, 12]])
np.concatenate([arr1,arr2],axis = 1)

Out[333]:

array([[ 1, 2, 3, 7, 8, 9],
[ 4, 5, 6, 10, 11, 12]])

In [334]:

import numpy as np

# splitting a string
print(np.char.join('-', 'geeks'))

# splitting a string
print(np.char.join(['-', ':'], ['geeks', 'for']))

g-e-e-k-s
['g-e-e-k-s' 'f:o:r']

In [ ]:

localhost:8888/notebooks/NUMPY .ipynb 32/32

Das könnte Ihnen auch gefallen