NumPy provides two fundamental objects for multi-dimensional arrays: the N-dimensional array object (ndarray) and the universal function object (ufunc). An ndarray is a homogeneous collection of items indexed using N integers. The shape and data type define an ndarray. NumPy arrays have a dtype attribute that returns the data type layout. Arrays can be created using the array() function and have various dimensions like 0D, 1D, 2D and 3D.
This is the basic introduction of the pandas library, you can use it for teaching this library for machine learning introduction. This slide will be able to help to understand the basics of pandas to the students with no coding background.
Introduction to Pandas and Time Series Analysis [PyCon DE]Alexander Hendorf
Most data is allocated to a period or to some point in time. We can gain a lot of insight by analyzing what happened when. The better the quality and accuracy of our data, the better our predictions can become.
Unfortunately the data we have to deal with is often aggregated for example on a monthly basis, but not all months are the same, they may have 28 days, 31 days, have four or five weekends,…. It’s made fit to our calendar that was made fit to deal with the earth surrounding the sun, not to please Data Scientists.
Dealing with periodical data can be a challenge. This talk will show to how you can deal with it with Pandas.
Abstract: This PDSG workshop introduces the basics of Python libraries used in machine learning. Libraries covered are Numpy, Pandas and MathlibPlot.
Level: Fundamental
Requirements: One should have some knowledge of programming and some statistics.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
This is the basic introduction of the pandas library, you can use it for teaching this library for machine learning introduction. This slide will be able to help to understand the basics of pandas to the students with no coding background.
Introduction to Pandas and Time Series Analysis [PyCon DE]Alexander Hendorf
Most data is allocated to a period or to some point in time. We can gain a lot of insight by analyzing what happened when. The better the quality and accuracy of our data, the better our predictions can become.
Unfortunately the data we have to deal with is often aggregated for example on a monthly basis, but not all months are the same, they may have 28 days, 31 days, have four or five weekends,…. It’s made fit to our calendar that was made fit to deal with the earth surrounding the sun, not to please Data Scientists.
Dealing with periodical data can be a challenge. This talk will show to how you can deal with it with Pandas.
Abstract: This PDSG workshop introduces the basics of Python libraries used in machine learning. Libraries covered are Numpy, Pandas and MathlibPlot.
Level: Fundamental
Requirements: One should have some knowledge of programming and some statistics.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
( Python Training: https://www.edureka.co/python )
This Edureka Python Numpy tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) explains what exactly is Numpy and how it is better than Lists. It also explains various Numpy operations with examples.
Check out our Python Training Playlist: https://goo.gl/Na1p9G
This tutorial helps you to learn the following topics:
1. What is Numpy?
2. Numpy v/s Lists
3. Numpy Operations
4. Numpy Special Functions
A Beginner's Guide to Machine Learning with Scikit-LearnSarah Guido
Given at the PyData NYC 2013 conference (http://vimeo.com/79517341), and will be given at PyTennessee 2014.
Scikit-learn is one of the most well-known machine learning Python modules in existence. But how does it work, and what, for that matter, is machine learning? For those with programming experience but who are new to machine learning, this talk gives a beginner-level overview of how machine learning can be useful, important machine learning concepts, and how to implement them with scikit-learn. We’ll use real world data to look at supervised and unsupervised machine learning algorithms and why scikit-learn is useful for performing these tasks.
This document is useful when use with Video session I have recorded today with execution, This is document no. 2 of course "Introduction of Data Science using Python". Which is a prerequisite of Artificial Intelligence course at Ethans Tech.
Disclaimer: Some of the Images and content have been taken from Multiple online sources and this presentation is intended only for Knowledge Sharing
Introduction to Python Pandas for Data AnalyticsPhoenix
Pandas is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python with Pandas is used in a wide range of fields including academic and commercial domains including finance, economics, Statistics, analytics, medical...
Presentation on data preparation with pandasAkshitaKanther
Data preparation is the first step after you get your hands on any kind of dataset. This is the step when you pre-process raw data into a form that can be easily and accurately analyzed. Proper data preparation allows for efficient analysis - it can eliminate errors and inaccuracies that could have occurred during the data gathering process and can thus help in removing some bias resulting from poor data quality. Therefore a lot of an analyst's time is spent on this vital step.
( Python Training: https://www.edureka.co/python )
This Edureka Python Numpy tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) explains what exactly is Numpy and how it is better than Lists. It also explains various Numpy operations with examples.
Check out our Python Training Playlist: https://goo.gl/Na1p9G
This tutorial helps you to learn the following topics:
1. What is Numpy?
2. Numpy v/s Lists
3. Numpy Operations
4. Numpy Special Functions
A Beginner's Guide to Machine Learning with Scikit-LearnSarah Guido
Given at the PyData NYC 2013 conference (http://vimeo.com/79517341), and will be given at PyTennessee 2014.
Scikit-learn is one of the most well-known machine learning Python modules in existence. But how does it work, and what, for that matter, is machine learning? For those with programming experience but who are new to machine learning, this talk gives a beginner-level overview of how machine learning can be useful, important machine learning concepts, and how to implement them with scikit-learn. We’ll use real world data to look at supervised and unsupervised machine learning algorithms and why scikit-learn is useful for performing these tasks.
This document is useful when use with Video session I have recorded today with execution, This is document no. 2 of course "Introduction of Data Science using Python". Which is a prerequisite of Artificial Intelligence course at Ethans Tech.
Disclaimer: Some of the Images and content have been taken from Multiple online sources and this presentation is intended only for Knowledge Sharing
Introduction to Python Pandas for Data AnalyticsPhoenix
Pandas is an open-source, BSD-licensed Python library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Python with Pandas is used in a wide range of fields including academic and commercial domains including finance, economics, Statistics, analytics, medical...
Presentation on data preparation with pandasAkshitaKanther
Data preparation is the first step after you get your hands on any kind of dataset. This is the step when you pre-process raw data into a form that can be easily and accurately analyzed. Proper data preparation allows for efficient analysis - it can eliminate errors and inaccuracies that could have occurred during the data gathering process and can thus help in removing some bias resulting from poor data quality. Therefore a lot of an analyst's time is spent on this vital step.
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
Homework Assignment – Array Technical Document
Write a technical document that describes the structure and use of arrays. The document should
be 3 to 5 pages and include an Introduction section, giving a brief synopsis of the document and
arrays, a Body section, describing arrays and giving an annotated example of their use as a
programming construct, and a conclusion to revisit important information about arrays described
in the Body of the document. Some suggested material to include:
Declaring arrays of various types
Array pointers
Printing and processing arrays
Sorting and searching arrays
Multidimensional arrays
Indexing arrays of various dimension
Array representation in memory by data type
Passing arrays as arguments
If you find any useful images on the Internet, you can use them as long as you cite the source in
end notes.
Solution
Array is a collection of variables of the same type that are referenced by a common name.
Specific elements or variables in the array are accessed by means of index into the array.
If taking about C, In C all arrays consist of contiguous memory locations. The lowest address
corresponds to the first element in the array while the largest address corresponds to the last
element in the array.
C supports both single and multi-dimensional arrays.
1) Single Dimension Arrays:-
Syntax:- type var_name[size];
where type is the type of each element in the array, var_name is any valid identifier, and size is
the number of elements in the array which has to be a constant value.
*Array always use zero as index to first element.
The valid indices for array above are 0 .. 4, i.e. 0 .. number of elements - 1
For Example :- To load an array with values 0 .. 99
int x[100] ;
int i ;
for ( i = 0; i < 100; i++ )
x[i] = i ;
To determine to size of an array at run time the sizeof operator is used. This returns the size in
bytes of its argument. The name of the array is given as the operand
size_of_array = sizeof ( array_name ) ;
2) Initialisg array:-
Arrays can be initialised at time of declaration in the following manner.
type array[ size ] = { value list };
For Example :-
int i[5] = {1, 2, 3, 4, 5 } ;
i[0] = 1, i[1] = 2, etc.
The size specification in the declaration may be omitted which causes the compiler to count the
number of elements in the value list and allocate appropriate storage.
For Example :- int i[ ] = { 1, 2, 3, 4, 5 } ;
3) Multidimensional array:-
Multidimensional arrays of any dimension are possible in C but in practice only two or three
dimensional arrays are workable. The most common multidimensional array is a two
dimensional array for example the computer display, board games, a mathematical matrix etc.
Syntax :type name [ rows ] [ columns ] ;
For Example :- 2D array of dimension 2 X 3.
int d[ 2 ] [ 3 ] ;
A two dimensional array is actually an array of arrays, in the above case an array of two integer
arrays (the rows) each with three elements, and is stored row-wise in memory.
For Example :- Program to fill .
Other than some generic containers like list, Python in its definition can also handle containers with specified data types. Array can be handled in python by module named “array“. They can be useful when we have to manipulate only a specific data type values.
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkual...HendraPurnama31
Matplotlib adalah pustaka plotting 2D Python yang menghasilkan gambar berkualitas publikasi dalam berbagai format cetak dan lingkungan interaktif di berbagai platform.
Opendatabay - Open Data Marketplace.pptxOpendatabay
Opendatabay.com unlocks the power of data for everyone. Open Data Marketplace fosters a collaborative hub for data enthusiasts to explore, share, and contribute to a vast collection of datasets.
First ever open hub for data enthusiasts to collaborate and innovate. A platform to explore, share, and contribute to a vast collection of datasets. Through robust quality control and innovative technologies like blockchain verification, opendatabay ensures the authenticity and reliability of datasets, empowering users to make data-driven decisions with confidence. Leverage cutting-edge AI technologies to enhance the data exploration, analysis, and discovery experience.
From intelligent search and recommendations to automated data productisation and quotation, Opendatabay AI-driven features streamline the data workflow. Finding the data you need shouldn't be a complex. Opendatabay simplifies the data acquisition process with an intuitive interface and robust search tools. Effortlessly explore, discover, and access the data you need, allowing you to focus on extracting valuable insights. Opendatabay breaks new ground with a dedicated, AI-generated, synthetic datasets.
Leverage these privacy-preserving datasets for training and testing AI models without compromising sensitive information. Opendatabay prioritizes transparency by providing detailed metadata, provenance information, and usage guidelines for each dataset, ensuring users have a comprehensive understanding of the data they're working with. By leveraging a powerful combination of distributed ledger technology and rigorous third-party audits Opendatabay ensures the authenticity and reliability of every dataset. Security is at the core of Opendatabay. Marketplace implements stringent security measures, including encryption, access controls, and regular vulnerability assessments, to safeguard your data and protect your privacy.
Show drafts
volume_up
Empowering the Data Analytics Ecosystem: A Laser Focus on Value
The data analytics ecosystem thrives when every component functions at its peak, unlocking the true potential of data. Here's a laser focus on key areas for an empowered ecosystem:
1. Democratize Access, Not Data:
Granular Access Controls: Provide users with self-service tools tailored to their specific needs, preventing data overload and misuse.
Data Catalogs: Implement robust data catalogs for easy discovery and understanding of available data sources.
2. Foster Collaboration with Clear Roles:
Data Mesh Architecture: Break down data silos by creating a distributed data ownership model with clear ownership and responsibilities.
Collaborative Workspaces: Utilize interactive platforms where data scientists, analysts, and domain experts can work seamlessly together.
3. Leverage Advanced Analytics Strategically:
AI-powered Automation: Automate repetitive tasks like data cleaning and feature engineering, freeing up data talent for higher-level analysis.
Right-Tool Selection: Strategically choose the most effective advanced analytics techniques (e.g., AI, ML) based on specific business problems.
4. Prioritize Data Quality with Automation:
Automated Data Validation: Implement automated data quality checks to identify and rectify errors at the source, minimizing downstream issues.
Data Lineage Tracking: Track the flow of data throughout the ecosystem, ensuring transparency and facilitating root cause analysis for errors.
5. Cultivate a Data-Driven Mindset:
Metrics-Driven Performance Management: Align KPIs and performance metrics with data-driven insights to ensure actionable decision making.
Data Storytelling Workshops: Equip stakeholders with the skills to translate complex data findings into compelling narratives that drive action.
Benefits of a Precise Ecosystem:
Sharpened Focus: Precise access and clear roles ensure everyone works with the most relevant data, maximizing efficiency.
Actionable Insights: Strategic analytics and automated quality checks lead to more reliable and actionable data insights.
Continuous Improvement: Data-driven performance management fosters a culture of learning and continuous improvement.
Sustainable Growth: Empowered by data, organizations can make informed decisions to drive sustainable growth and innovation.
By focusing on these precise actions, organizations can create an empowered data analytics ecosystem that delivers real value by driving data-driven decisions and maximizing the return on their data investment.
Explore our comprehensive data analysis project presentation on predicting product ad campaign performance. Learn how data-driven insights can optimize your marketing strategies and enhance campaign effectiveness. Perfect for professionals and students looking to understand the power of data analysis in advertising. for more details visit: https://bostoninstituteofanalytics.org/data-science-and-artificial-intelligence/
As Europe's leading economic powerhouse and the fourth-largest hashtag#economy globally, Germany stands at the forefront of innovation and industrial might. Renowned for its precision engineering and high-tech sectors, Germany's economic structure is heavily supported by a robust service industry, accounting for approximately 68% of its GDP. This economic clout and strategic geopolitical stance position Germany as a focal point in the global cyber threat landscape.
In the face of escalating global tensions, particularly those emanating from geopolitical disputes with nations like hashtag#Russia and hashtag#China, hashtag#Germany has witnessed a significant uptick in targeted cyber operations. Our analysis indicates a marked increase in hashtag#cyberattack sophistication aimed at critical infrastructure and key industrial sectors. These attacks range from ransomware campaigns to hashtag#AdvancedPersistentThreats (hashtag#APTs), threatening national security and business integrity.
🔑 Key findings include:
🔍 Increased frequency and complexity of cyber threats.
🔍 Escalation of state-sponsored and criminally motivated cyber operations.
🔍 Active dark web exchanges of malicious tools and tactics.
Our comprehensive report delves into these challenges, using a blend of open-source and proprietary data collection techniques. By monitoring activity on critical networks and analyzing attack patterns, our team provides a detailed overview of the threats facing German entities.
This report aims to equip stakeholders across public and private sectors with the knowledge to enhance their defensive strategies, reduce exposure to cyber risks, and reinforce Germany's resilience against cyber threats.
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Subhajit Sahu
Abstract — Levelwise PageRank is an alternative method of PageRank computation which decomposes the input graph into a directed acyclic block-graph of strongly connected components, and processes them in topological order, one level at a time. This enables calculation for ranks in a distributed fashion without per-iteration communication, unlike the standard method where all vertices are processed in each iteration. It however comes with a precondition of the absence of dead ends in the input graph. Here, the native non-distributed performance of Levelwise PageRank was compared against Monolithic PageRank on a CPU as well as a GPU. To ensure a fair comparison, Monolithic PageRank was also performed on a graph where vertices were split by components. Results indicate that Levelwise PageRank is about as fast as Monolithic PageRank on the CPU, but quite a bit slower on the GPU. Slowdown on the GPU is likely caused by a large submission of small workloads, and expected to be non-issue when the computation is performed on massive graphs.
2. Object Essentials
NumPy provides two fundamental objects:
1. An N-dimensional Array Object (Ndarray)
2. A universal function object (ufunc).
An N-dimensional array: a homogeneous collection of “items” indexed
using N integers.
Two essential pieces of information that define an N-dimensional array:
1. The Shape Of The Array
2. The kind of item the array is composed of
5. # DataType Output: str
x = "Hello World"
# DataType Output: int
x = 50
# DataType Output: float
x = 60.5
# DataType Output: complex
x = 3j
# DataType Output: list
x = ["geeks", "for", "geeks"]
# DataType Output: tuple
x = ("geeks", "for", "geeks")
# DataType Output: bytearray
x = bytearray(4)
# DataType Output: memoryview
x = memoryview(bytes(6))
# DataType Output: NoneType
x = None
# DataType Output: range
x = range(10)
# DataType Output: dict
x = {"name": "Suraj", "age": 24}
# DataType Output: set
x = {"geeks", "for", "geeks"}
# DataType Output: frozenset
x = frozenset({"geeks", "for", "geeks"})
# DataType Output: bool
x = True
# DataType Output: bytes
x = b"Geeks"
6. Create a NumPy ndarray Object
using the array() function
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
7. Create a NumPy ndarray Object
Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
print(type(arr))
8. Dimensions in Arrays
0-D Arrays
The elements in array are 0-D arrays, or Scalars.
Example: Create a 0-D array with value 862
import numpy as np
arr = np.array(862)
print(arr)
9. Dimensions in Arrays
1-D Arrays
An array that has 1-D arrays as its elements is called uni-
dimensional or 1-D array.
Example: Create a 0-D array with value 1,2,3,4,5
import numpy as np
arr = np.array([1,2,3,4,5])
print(arr)
10. Dimensions in Arrays
2-D Arrays
An array that has 1-D arrays as its
elements is called two-dimensional or 2-
D array.
Example: Create a 2-D array with values
1,2,3 and 4,5,6
import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
print(arr)
11. Dimensions in Arrays
3-D Arrays
An array that has 2-D arrays as its elements is
called three-dimensional or 3-D array.
Example: Create a 3-D array with 2 D array values
1,2,3 and 4,5,6
import numpy as np
arr = np.array([[[1,2,3],[4,5,6]], [[1,2,3],[4,5,6]]])
print(arr)
12. Check Number of Dimensions?
NumPy Arrays provides the ndim attribute that returns an integer that tells us how
many dimensions the array have.
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
13. Higher Dimensional Arrays
An array can have any number of dimensions.
When the array is created, we can define the
number of dimensions by using the ndmin
argument.
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
14. Array Indexing
• Get the first element from a 1D array
• Get third and fourth elements from a 1D array and add them.
• To access elements from 2-D arrays we can use comma separated
integers representing the dimension and the index of the element.
• Access the element on the first row, second column
• Access the element on the 2nd row, 5th column
15. Array Indexing
• To access elements from 3-D arrays we can use comma
separated integers representing the dimensions and the index
of the element.
• Access the third element of the second array of the first array
• Negative Indexing
• Use negative indexing to access an array from the end.
17. Data Types in Python
By default Python have these data types:
Strings - used to represent text data
Integer - used to represent integer numbers.
Float - used to represent real numbers.
Boolean - used to represent true or false.
Complex - used to represent complex numbers.
18. Data Types in NumPy
NumPy has some extra data types, and refer to data types with
one character
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - timedelta
M - datetime
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
19. Checking the Data Type of an Array
The NumPy array object has a property called dtype that
returns the data type of the array:
Example:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
20. Creating Arrays With a Defined Data Type
Use array() function to create arrays, this can take an optional
argument: dtype to define the expected data type of the array
elements:
Example:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S’)
print(arr)
print(arr.dtype)
21. Converting Data Type on Existing Arrays
The best way to change the data type of an existing array, is to make a
copy of the array with the astype() method.
The astype() function creates a copy of the array, and allows you to
specify the data type as a parameter.
Example:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i’)
print(newarr)
print(newarr.dtype)
22. NumPy Array Copy vs View
• The main difference between a copy and a view of an array is that
the copy is a new array, and the view is just a view of the original
array.
• The copy owns the data and any changes made to the copy will not
affect original array, and any changes made to the original array will
not affect the copy.
• The view does not own the data and any changes made to the view
will affect the original array, and any changes made to the original
array will affect the view.
23. NumPy Array Copy vs View
Example:
COPY
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
24. NumPy Array Copy vs View
Example:
VIEW
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)
25. Array Slicing
• Taking elements from one given index to another given index.
• We pass slice instead of index like this: [start:end].
• We can also define the step, like this: [start:end:step].
• If we don't pass start it’s considered 0
• If we don't pass end it’s considered length of array in that
dimension
• If we don't pass step it’s considered 1
26. Array Slicing
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
//Slice elements from index 1 to index 5
print(arr[1:5])
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
//Slice elements from index 4 to the end of the array:
print(arr[4:])
27. Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
//Slice elements from the beginning to index 4 (not included):
print(arr[:4])
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
28. Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
//Return every other element from index 1 to index 5:
print(arr[1:5:2])
//Return every other element from the entire array:
print(arr[::2])
29. Taking array and elements from one given index to another given index.
We pass slice instead of index like this:[array index, start:end].
We can also define the step, like this: [array index, start:end:step].
2 D array has two 1D arrays
array index 0 for first 1D array
array index 1 for first 1D array
Slicing 2-D Arrays
30. Slicing 2-D Arrays
Example:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
//From the second element, slice elements from index 1 to index 4 (not included):
print(arr[1,1:4])
Example:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
//From both elements, return index 2:
print(arr[0:2,2])
31. Example:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
//From both elements, slice index 1 to index 4 (not included):
print(arr[0:2,1:4])
32. Array Shape
Shape of an Array
The shape of an array is the number of elements in each dimension.
NumPy arrays have an attribute called shape that returns a tuple with
each index having the number of corresponding elements.
Example:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
33. Array Reshaping
• Reshaping means changing the shape of an array.
• The shape of an array is the number of elements in each
dimension.
• By reshaping we can add or remove dimensions or change
number of elements in each dimension.
34. Reshape From 1-D to 2-D
Example:
Convert the following 1-D array with 12 elements into a 2-D array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
//The outermost dimension will have 4 arrays, each with 3 elements:
print(newarr)
35. Reshape From 1-D to 3-D
Example:
Convert the following 1-D array with 12 elements into a 3-D array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3,2)
//The outermost dimension will have 2 arrays that contain 3 arrays, each with 2 elements:
print(newarr)
36. Unknown Dimension
You are allowed to have one "unknown" dimension.
Do not specify an exact number for one of the dimensions in
the reshape method.
Pass -1 as the value, and NumPy will calculate this number for
you.
37. Unknown Dimension
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(2, 2, -1)
print(newarr)
//Convert 1D array with 8 elements to 3D array with 2x2 elements:
38. Flattening the arrays
Means converting a multidimensional array into a 1D array.
Use reshape(-1) to do this.
Example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr) newarr = arr.reshape(-1)
//Convert the array into a 1D array:
print(newarr)
40. Iterating Arrays
• Iterating means going through elements one by one.
• As we deal with multi-dimensional arrays in numpy, we can do this
using basic for loop of python.
• If we iterate on a 1-D array it will go through each element one by one.
Example:
import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)
41. Iterating 2-D Arrays
In a 2-D array it will go through all the rows.
Example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
If we iterate on a n-D array it will go through
n-1th dimension one by one.
42. Iterating 2-D Arrays
To return the actual values, the scalars, we have to iterate the
arrays in each dimension.
Example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
43. Iterating 3-D Arrays
In a 3-D array it will go through all 2D arrays.
Example:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)
[[1 2 3]
[4 5 6]]
[[ 7 8 9]
[10 11 12]]
44. Iterating 3-D Arrays
In a 3-D array it will go through all 2D arrays.
Example:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)
1
2
3
4
5
6
7
8
9
10
11
12
45. Iterating Arrays Using nditer()
Example 1:
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for x in np.nditer(arr):
print(x)
46. Iterating With Different Step Size
Iterate through every scalar element of the
2D array skipping 1 element:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
for x in np.nditer(arr[:, ::2]):
print(x)
48. Joining NumPy Arrays
Joining means putting contents of two or more arrays in a
single array.
In SQL we join tables based on a key, whereas in NumPy
we join arrays by axes.
We pass a sequence of arrays that we want to join to the
concatenate() function, along with the axis, If axis is not
explicitly passed, it is taken as 0.
55. Joining Arrays Using Stack Functions
Stacking is same as concatenation, the only difference is that
stacking is done along a new axis.
We can concatenate two 1-D arrays along the second axis which
would result in putting them one over the other, i.e,. stacking.
We pass a sequence of arrays that we want to join to the stack()
method along with the axis. If axis is not explicitly passed it is taken
as 0 (default).
56. Joining Arrays Using Stack Functions
Stack Two 1D arrays:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.stack((arr1, arr2), axis=1)
print(arr)
57. Joining Arrays Using Stack Functions
Stacking Along Rows:
NumPy provides a helper function: hstack() to stack along rows.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.hstack((arr1, arr2))
print(arr)
58. Joining Arrays Using Stack Functions
Stacking Along Colum:
NumPy provides a helper function: vstack() to stack along coloum.
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.vstack((arr1, arr2))
print(arr)
59. Joining Arrays Using Stack Functions
Stacking Along Height (depth)
NumPy provides a helper function: dstack() to stack along height,
which is the same as depth.
import numpy as np
arr1 = np.array([[1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.dstack((arr1, arr2))
print(arr)
61. ufuncs are used to implement vectorization in NumPy which is way faster than
iterating over elements.
They also provide broadcasting and additional methods like reduce, accumulate
etc. that are very helpful for computation.
ufuncs also take additional arguments, like:
where boolean array or condition defining where the operations should take
place.
dtype defining the return type of elements.
out output array where the return value should be copied.
62. Vectorization
Converting iterative statements into a vector based operation is called
vectorization.
It is faster as modern CPUs are optimized for such operations.
Add the Elements of Two Lists
list 1: [1, 2, 3, 4]
list 2: [4, 5, 6, 7]
One way of doing it is to iterate over both of the lists and then sum each
elements.
63. Example
Without ufunc, we can use Python's built-in zip() method:
x = [1, 2, 3, 4]
y = [4, 5, 6, 7,9]
z = []
for i, j in zip(x, y):
z.append(i + j)
print(z)
OUTPUT
[5, 7, 9, 11]
64. NumPy has a ufunc for this, called add(x, y) that will produce the same
result.
Example
With ufunc, we can use the add() function:
import numpy as np
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = np.add(x, y)
print(z)
OUTPUT
[5, 7, 9, 11]
65. Create Your Own ufun
1. define a function like normal python program
2. add it to your NumPy ufunc library with the frompyfunc()
method
The frompyfunc() method takes the following arguments:
1. Function name - the name of the function we defined.
2. inputs - the number of input arguments (arrays) to be
passed.
3. outputs - the number of output arrays returned.
68. Simple Arithmetic
Addition:
The add() function sums the content of two arrays, and return the results in a
new array.
Example:
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.add(arr1, arr2)
print(newarr)
OUTPUT
[30 32 34 36 38 40]
69. Subtraction:
The subtract() function subtracts the values from one array with the
values from another array, and return the results in a new array.
Example:
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.subtract(arr1, arr2)
print(newarr)
[-10 -1 8 17 26 35]
70. Multiplication:
The multiply() function multiplies the values from one array with
the values from another array, and return the results in a new array.
Example:
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.multiply(arr1, arr2)
print(newarr)
[ 200 420 660 920 1200 1500]
71. Division:
The divide() function divides the values from one array with the
values from another array, and return the results in a new array.
Example:
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([3, 5, 10, 8, 2, 33])
newarr = np. divide(arr1, arr2)
print(newarr)
[ 3.33333333 4. 3. 5. 25. 1.81818182]
73. Rounding Decimals
There are primarily five ways of rounding off
decimals in NumPy:
* truncation
* fix
* rounding
* floor
* ceil
74. Rounding Decimals
Truncation:
Remove the decimals, and return the float number closest to zero. Use
the trunc() and fix() functions.
Eg:
import numpy as np
arr = np.trunc([-3.1666, 3.6667])
print(arr)
Eg:
import numpy as np
arr = np.fix([-3.1666, 3.6667])
print(arr)
[-3. 3.]
[-3. 3.]
75. Rounding
The around() function increments preceding digit or decimal by 1 if >=5
else do nothing.
Eg:
import numpy as np
arr = np.around([3.1666, 2])
print(arr)
import numpy as np
arr = np.around([3.1666, 2.6, 1.6, 4.3])
print(arr)
[3. 2.]
[3. 3. 2. 4.]
76. Floor:
The floor() function rounds off decimal to nearest lower integer.
Eg:
import numpy as np
arr = np. floor([-3.1666, 3.6667])
print(arr)
[-4. 3.]
77. Ceil:
The ceil() function rounds off decimal to nearest upper integer.
Eg:
import numpy as np
arr = np. ceil([-3.1666, 3.6667])
print(arr)
[-3. 4.]
79. Splitting Array
• Splitting is reverse operation of Joining.
• Joining merges multiple arrays into one and Splitting breaks one
array into multiple.
• We use array_split() and split() for splitting arrays, we pass it the
array we want to split and the number of splits.
80. Splitting Array
Example://split a 1D array to 3 parts
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.split(arr, 3)
print(newarr)
[array([1, 2]), array([3, 4]), array([5, 6])]
81. Example://split a 1D array to 3 parts
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.split(arr, 4)
print(newarr)
82. Splitting Array
Example://split a 1D array to 3 parts
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np. array_split (arr, 4)
print(newarr)
[array([1, 2]), array([3, 4]), array([5]), array([6])]
84. Splitting 2-D Arrays
Use the same syntax when splitting 2-D arrays.
Use the array_split() method, pass in the array you want to split
and the number of splits you want to do.
Example:
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)
[array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]]), array([[ 9, 10],
[11, 12]])]
85. Splitting 2-D Arrays
In addition, you can specify which axis you want to do the split
around.
The example below also returns three 2-D arrays, but they are
split along the row (axis=1).
Example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],
[13, 14, 15], [16, 17, 18]])
newarr = np.array_split(arr, 3, axis=1)
print(newarr)
[array([[ 1],
[ 4],
[ 7],
[10],
[13],
[16]]), array([[ 2],
[ 5],
[ 8],
[11],
[14],
[17]]), array([[ 3],
[ 6],
[ 9],
[12],
[15],
[18]])]