0% found this document useful (0 votes)
17 views10 pages

Adobe Scan Sep 03 2024

The document provides an introduction to NumPy arrays, covering their creation, indexing, slicing, and various operations. It includes exercises and examples for manipulating arrays, as well as a detailed explanation of NumPy's standard data types. Additionally, it discusses array concatenation, splitting, and reshaping, along with universal functions for computational tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views10 pages

Adobe Scan Sep 03 2024

The document provides an introduction to NumPy arrays, covering their creation, indexing, slicing, and various operations. It includes exercises and examples for manipulating arrays, as well as a detailed explanation of NumPy's standard data types. Additionally, it discusses array concatenation, splitting, and reshaping, along with universal functions for computational tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Text time.

are either
There
arrays
Date: Score: a in NumPy
Intermediate at
valuetype.arrays
Hence
(length-1).
one same arrays.
create ordered.
Exercises
Programming
Based than
theto with
moreof is are to
account. list 0from
index.
elements working
Numpy Arrays negative
hold to: library the range
expected
and Colab in
Numpy can of for Python
with
NumPy elements a
of functions
3: whichnumber
used ListsPython
Google
Indices using Eng
Exercise
to
Introduction variable,the
library
are Python
students default
their
i.e.,subscript.
back
the
tist.
a Syntax:
list_name[start:stop:step] Bios
fixed object, of
of a with sub-sequence
from odd_num[0:5])
a One is in to odd_num:5]))
hold Numpy
special the themselves
arrays
arays in or
sequence print("List
elements:",
odd_num[0])
accessed
print("List
elements:",
odd_num[-1) odd_num) 0
arrays. log index index
Laboratory
and
Python a
can
is than1D-4D
integers.
chapter,
codecode
to to
need Slicing:
and
Indexing
using
_num)
Odd_num=
(1,3,5,7,9,11,13,15]
odd extractinga
odd_num
=[1,3,5,7,9,11,13,15]
assumes
elements:",
:",

&
Agri
Section: Introduction
Python this
Familiarize
to Methodology isa be are:",
Objectives will accessed elements:",also elements
structure ableable
Be list of
in signed
array, lists of student a index
elements
Arays in end Be Indexing:
can Engi
& Arrays of than elements is fivestartfive
Level the
data bit are
elements Slicing Unt
and types The print("List print("First
Name: 64 faster At Example:
# print("List
slicing
print("First
#omitting
Year Lists a or III.
is four32 are I. #list lMin
t
of
Cen
Colle
subscript using
done
-first
be
subscripts Can
list.
a colors)
two of
position
requires
list. nested_list[OJ2)
odd_num[0:5:2) list) beginning,:"
odd_num[5:]) len(nested inner nested_list[1:])
any pandavas)
object. objects
the colors) pandavas)
at pandavas)"Arjun"]
odd_num[-5:]) Falsel] for
is:",
inserted "Arjun"]
elements
list :", list list:", listssubscriptnested_list[2]) appending:",the pandavas.extend
(["Nakul",
"Sahadev"]) ",
print("Concatenat
pandavas+12)
of fifth [True, nested list elementare:" be extend
at extending:", "Bheem",concatenation
"Bheem",
end:"
onwards a
of colors) inserting
more
extending:", 2)
element the
asSumesto up elements:" "Arjun", nested
second element first can
objects: ",
elementsfiprint("Last
ve
print("Alternative in
elementsslicing
of list
first than Element
or or Dharmaraj",
concatenati
element lists is:", the are:",
insert "Green"]
=["Red", after
colors
element
after oneDharmaraj",
before
12
=["Nakul",
"Sahadev"]
index index #using -an [[1,2,3),
negative -nested the of
slicingfirstof of other Lists element
#Appending
colors.insert(0,"White")
colors.append("Blue") after List after
element member
elements or
Insertion:
element
elements elements elements with #concatenation
Lists list) and and
print(nested_
of of on append first
stop5thsize
step
#using print("Number member print("Elements list print("Pandavas
print("Pandavas print("pandavas
print("From
omitting
NestedLists
list
list and
Indexing
print("Third
outer Indexing print("Third
Methods
an as
Inserting
print("List
the
["
=
print("Listpandavas
["
=
pandavas
after
two print("List
of
nested_ Third 1.
append Extend print("2
#List the last
# for # # # # # #
to
commands
num)
slice
even_num)
even and keyword
Engi
", even_num) type()
even_num)
2: dtype
:, index even_num) the
element use the Bios
)even_num.pop()
at del:", pop:"
element and use
list even_num)
_num) deletion:" Lists array,dtype=np.float32)
np.array([1,2,3,4],
X=
the last using using list list. &
from poppingpopping float Python Python resulting
Ag
even index index the 9])
element 4deletion:",
(2,even_num=
,6,8,4,10] [2,4,6,8,4,10]
even_num=
element:, =[2,4,6,8,10,12]
even_num
before 3rd
and in L]
in
8,
7, from
1the
specified
even_num.
deletion remove(4)after after
:",
elements at at
3rd is
int, type
string,
item in
Arrays 6,
5, Arrays np 3])
before the
of
of
PE
elements elements
even_num.pop(2) deletiondeletion data 4] L)A=array.array('t,
before even_num.pop(3)
even_num[3]
del 3.0,for Fixed-Type 4,
list(range(10))
L= 3,
5,
2, 3.14
type
after method
#pop Deleted Print[type(item) as
Creating
a NumPy what "2", 1, array4,
numpy#nteger
np.array((1, data
Deleteaprint("List
print("List print("List
method
#del print("After Create
print("After
print("List print("List #Example:
determine
import
array (0, putting
L=[True, Array('t, the print(X)
print(' Import
#try set
# A To
array
#make a multidimensional
y=np.array([range(i, i+3) for l in (2,3,6))
print(y)

Try yourself:
array filled with Os
8. Create a length-10integer filled with 19
point array
b. Create a 3x5 floating
filled with 3.14
C. Create a 3x5 array
a linear sequence
d. Create an array filled with and 1
values evenly spaced between 0
e. Create an array of five distributed
f. Create a3x3 array of uniformly
distributed pseudorandom
g. Create a 3x3 array of normally
integers in the interval 0, 10
h. Crate a 3x3 array of pseudorandom
i. Create a 3x3 identity matrix

NUMPY STANDARD DATA TYPES

Table 4-1. Standard NumPy data types

Data type Description


bool_
Boolean (True ot False) stofed as a byte
int_ Defaut integer type (same as ( long; nofmally either int64 of int32)
intc dentcal to Cint (nofmally int32 or int64)
intp Integef used for indexing (same as (ssize_t; nofmally either int32 or int64)
int8 Byte (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147433648 to 2147483647)
int64
Integer (-923372036354775808 to 92233720363547S807)
uint8 Unsigned integer (0 to 25S)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 4294967295)
uint64 Unsigned integer (0 to 184467440737O9551615)
float_ Shorthand for float64
float16 Half-precision float: sign bit, Sbits exponent, 10 bts mantissa
float32 Single-precision float: sign bit, 8bits exponent, 23 bits mantissa
float64 Double-precision float: sign bit, 11bits exponent, 52 bits mantissa
conplex_ Shorthand for conplex128
conplex64 Complex number, fepfesented by two 32-bit foats
conplex128 Complex numbet, lepresented by two 64-bit floats

Numpy array in diferent dimensions


import numpy as np
rng= np.random.default rng(seed=1701) # seed for reproducibility
x1 =rng.integers(10, size-6) # one-dimensional array
X2= rng.integers(10, size-(3, 4)) #two-dimensional array
X3 = rng.integers(10, size-(3, 4, 5)) # three-dimensional array

#math operations
print("x3 ndim:", x3.ndim)
ADEAB: computer Applleationn in AB Engineering

print("%3 shape:", N3.shope)


print("x3 size: ", x3.size)
print(°dtype: ", x3.dtype)

Array indexing: Accessing Single Elements


X1
x1[0)
x1[4]
x1[-1]

#indexing multidimensional array


x2
x2[0, 0]

#modification of index notation


x2[0, 0]= 12
X2

Array Slicing: Accessing Subarrays


x[start:stop:stop]
#1Dimensional Sub arrays
x1
x1[:3] #first three elements
x1[3:] #elements after index 3
x1[1:4] #middle subarray
x1(::2] #every second element
x1[1::2] #every second element, starting at index 1

Multidimensional Subarrays
X2

X2(:2.:3] #first twO rows &three columns


x2[:3,::2] #three rows, every second column
X2[::-1,::1]#all rows &columns, reversed

Accessing single rows or columns of an array.


X2[:. 0] #first column of x2
x2[0, :] #first row of x2
array([12, 1, 3, 7)
X2(0] #equivalent to x2[0. :]

Subarrays as No-Copy ViewS


print(x2)

Colloge ofEngineering
Central Mindanao Dopartrnernt of
University &
x2 sub=x2[:2, :2]
print(x2_sub)

#modifysub array
x2_sub[0,0]=99
print(x2sub)
print(x2)

Creating copies of arrays

x2_ sub_copy =x2[:2, :2].copy)


print(x2_sub_copy)
x2_sub_copy[0,0] =42
print(x2_sub_copy)
print(x2)

method
Reshaping arrays - can be done using the reshape

grid =np.arrange(1, 10).reshape(3, 3)


print(grid)
column matrix:
#converting one dimensional array into two-dimensional row or
X= np.array([1, 2, 3])
X.reshape((1, 3,)
X.reshape(3, 1)
#using np.newaxis in the slicing syntax
x(np.newaxis, :] #row vector via newaxis
X[, np.newaxis] #column vector via newaxis

Array Concatenation and Splitting


Concatenation of Arrays - takes a tuple or list of arrays as its first argument
X= np.array([1, 2, 3])
y= np.array([3, 2, 1])
np.concatenate([x, y])

Z= np.array([99, 99, 99])


print(np.concatenate([x, y, zl)
grid =np.array([[1, 2, 3],
[4,5,6])

np.concatenate([grid, grid])
#concatenate along the second axis (zero-indexed)
np.concatenate([grid, grid], axis = 1)

#vertically stack the arrays


np.vstack([,grid)

#horizontally stack the arrays


y=np.array([99],
[99])
np.hstack(grid, yl)

Solitting of Array - opposite of concatenation


1]1
x= [1, 2, 3, 99,99, 3, 2, 5))
x1, x2, x3 =np.split(x, (3,
print(x1,x2, x3)

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

Functions
Computational on NumPy Arrays: Universal
operations
Universal functions (ufuncs)- implements vectorized
import numpy as np
rng = np.random.default_rnglseed=1701)

def compute_reciprocals(values):
output = np.empty(len(values)
for iin range(len(values)):
output[i] =1.0 /values[i]
return output

values = rng.integers(1, 10, size=5)


compute_reciprocals(values)

Ufuncs

print(compute_reciprocals(values)
print(1.0/values)

%tineit (1.0 /big_array)


np.arrange(5)/ np.arrange(1,6)
x=np.arrange(9).reshape(3,3)
2**x

Exploring NumPy's Ufuncs:

Unary ufuncs: operate on a single input


Binary ufuncs: operate on two inputs
#Array Arithmetics:
1)
NumPy
in
ímplemented 8) =
6) 1)
1) = 4
= 1.5) = 3 % Logarithms
2) = 3 2 ** 9 (eg..
Modulus/temainder
= 2 -2) * = // 2
1 - (e.g,(e.g.,2 2/ 3 (e.g.,
3 (e.g,
1 (e.g.negation (eg,3 Exponentiaton
(e.g, Multiplication
division
Subtraction
Desaiption and
Addition Unaty Division
operators Floor Exponents
np.floor_divide
Arithmetic
6-1.
Tableufunc
Equivalent np.multiply
Operator np.subtract
np.negative np.cos(theta)
np.divide np.tan(theta)
print("sin(theta)
",np.sin(theta)
division.operators np.power
np.Pod functions, print("3^x=",
np.power(3.,
x))
np.add 3) #exponents
and
logarithms print("log2()
=",
np.log2()
np.pi,=",
theta) print("2^x=",
np.exp2(x) print("ln(x)
1,2]) #Trigonometric
Functions print("e^x=",
np.exp(x)) =",
np.log(x)
floor
arithmetic ", ",
np.linspace(0, trigonometric
-1,0, ==
# print("cos(theta)
5) *2)2) =X/2)
X=np.arrange(4) np.array([-2,
print("tan(theta)
print("x,
=",
x) 10]print("x
=",
x)
x+ -5) x/ Value
#absolutenp.absolute(x) print("theta np.arctan()
np.arccos(x)
np.arcsin() 3] 3,
=", x x=",
x)=",print("x =", other 2, 2,
2
=", print("x/2
+5 print("x-5 2
np.abs(x)
= Inverse (1, x=[1,
print("x*print("xIlprint("x doing
x=
abs(x) theta x=
Try
the
computing
are
These
functions.
exploration.
_array.sum()
aggregate
Betweon
data
_array np._array),
np.max(bi
min(big_array_
g big_array.max(),
in other big
in important
Everythingand rng.=
bigrandom(10000000)
deviation,
Array np.rnrg=andom.default_rng) max(bi min(big_array)
g_array), Functions:
(x)np.logtp(x)
=",print("log(1+x)
"xprint("log10(x)
np.log10(x))
1np.expm np.%tsum(big_array)
imeit Aggregates
Multidimnensional
#minimum np.%tmimin(big_array)
%timeit priit nt(big_array.min(),
4)
%timeitmaximum
and
are
and statisticsan sum(big_array) min(big_array) (3,
0.11 max standard
in
Valuos L=rng.random(100) 10,
ng.integers(0, aggregation
np
0.01,-1=" min, Summary as version
#another =0) 1)=
M.max(axis
M.min(axis
thenumpy
print("exp(*)Aggregations:
0.001, mean,#Summing np.sum(L) print(M)
M.sum) other
x-[0, import sum(L) M= Try
and with
dataset Working
that functions. for
Tools Springer.
ofregression
Essential
Science.
Exploration
Engineering
linear Handbook:
Data
elements
toe true
the NumPy for
Numy elemestsermt elements(ompute of ale ale compute Biosystems
standard
denaton vdue
minimum
value elementbssatisticselementsallelements Science Python
d vatunKeFnd
mnimum
vale Fnd maumum use
of ptodut meanod (ompute manmm
value
of tfank-bused any How? (2024).
in sum medun whetherwhether
availableDesoption
(ompute(ompute(ompute of
inder Desription
of use('
plt.steaborn-whi
yle. tegrid') you and
numpy? Conclusion Data &
Agricultural
can data,
index Compule (omputeFraluateEvaluate
fnd
Fnd plt questions: Python S.Vinayakam,
functions np.nanpercentile Matplotlib for as
Pseudocode
matplotlib.pypplot data, csv Edition
venion
Nal-sale np.nanprod np.nanargntnNal-safe of adownloading own (2024). of
Aggr7-Tabl1. egtion
np.nansun np.nanneannp.nanstd np.nannin
np.nanvar .nannax
np.nannedian
versionnp.nanargnax
inline
%matplotlib
name)
plt.hist(#xaxis Discussion agivenuse
following the
Conclusion
yOur References2nd
O'Reilly.&
J.VanderPlas,
Engineering-Department
np NIA NIA pltxlabel("#) are with Make L.
Muddana,
Mindanao
Universitu
Contral
naneFnction argntn
np.
np.percentile plt.title(#)plt.ylabel the you plot Try Data.
prodnp. np. std
nean np. varnp. np.ninnp.nax name np. nedian
np.
Functionargrax
import AnswerIf 2.
sUn
np. np.anynp.all IV. 1. V. VI
of
colege

You might also like