w3resource

NumPy Exercises, Practice, Solution

NumPy

NumPy is a Python package providing fast, flexible, and expressive data structures designed to make working with 'relationa' or 'labeled' data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python.

The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the NumPy concepts by solving the exercises starting from basic to more complex exercises. A sample solution is provided for each exercise. It is recommended to do these exercises by yourself first before checking the solution.

Hope, these exercises help you to improve your NumPy coding skills. Currently, following sections are available, we are working hard to add more exercises .... Happy Coding!

List of NumPy Exercises:

NumPy Basics

Operator Description
np.array([1,2,3]) 1d array
np.array([(1,2,3),(4,5,6)]) 2d array
np.arange(start,stop,step) range array

Placeholders

Operator Description
np.linspace(0,2,9) Add evenly spaced values btw interval to array of length
np.zeros((1,2)) Create and array filled with zeros
np.ones((1,2)) Creates an array filled with ones
np.random.random((5,5)) Creates random array
np.empty((2,2)) Creates an empty array

Array

Syntax Description
array.shape Dimensions (Rows,Columns)
len(array) Length of Array
array.ndim Number of Array Dimensions
array.dtype Data Type
array.astype(type) Converts to Data Type
type(array) Type of Array

Copying/Sorting

Operators Description
np.copy(array) Creates copy of array
other = array.copy() Creates deep copy of array
array.sort() Sorts an array
array.sort(axis=0) Sorts axis of array

Array Manipulation

Adding or Removing Elements

Operator Description
np.append(a,b) Append items to array
np.insert(array, 1, 2, axis) Insert items into array at axis 0 or 1
np.resize((2,4)) Resize array to shape(2,4)
np.delete(array,1,axis) Deletes items from array

Combining Arrays

Operator Description
np.concatenate((a,b),axis=0) Concatenates 2 arrays, adds to end
np.vstack((a,b)) Stack array row-wise
np.hstack((a,b)) Stack array column wise

Splitting Arrays

Operator Description
numpy.split() Split an array into multiple sub-arrays.
np.array_split(array, 3) Split an array in sub-arrays of (nearly) identical size
numpy.hsplit(array, 3) Split the array horizontally at 3rd index

More

Operator Description
other = ndarray.flatten() Flattens a 2d array to 1d
array = np.transpose(other)
array.T
Transpose array
inverse = np.linalg.inv(matrix) Inverse of a given matrix

Mathematics

Operations

Operator Description
np.add(x,y)
x + y
Addition
np.substract(x,y)
x - y
Subtraction
np.divide(x,y)
x / y
Division
np.multiply(x,y)
x @ y
Multiplication
np.sqrt(x) Square Root
np.sin(x) Element-wise sine
np.cos(x) Element-wise cosine
np.log(x) Element-wise natural log
np.dot(x,y) Dot product
np.roots([1,0,-4]) Roots of a given polynomial coefficients

Comparison

Operator Description
== Equal
!= Not equal
< Smaller than
> Greater than
<= Smaller than or equal
>= Greater than or equal
np.array_equal(x,y) Array-wise comparison

Basic Statistics

Operator Description
np.mean(array) Mean
np.median(array) Median
array.corrcoef() Correlation Coefficient
np.std(array) Standard Deviation

More

Operator Description
array.sum() Array-wise sum
array.min() Array-wise minimum value
array.max(axis=0) Maximum value of specified axis
array.cumsum(axis=0) Cumulative sum of specified axis

Slicing and Subsetting

Operator Description
array[i] 1d array at index i
array[i,j] 2d array at index[i][j]
array[i<4] Boolean Indexing, see Tricks
array[0:3] Select items of index 0, 1 and 2
array[0:2,1] Select items of rows 0 and 1 at column 1
array[:1] Select items of row 0 (equals array[0:1, :])
array[1:2, :] Select items of row 1
[comment]: <> ( array[1,...]
array[ : :-1] Reverses array

[ Want to contribute to Python Pandas exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: How to install pip on Windows?

Python 2.7.9+ and 3.4+

Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. In shipping with a package manager, Python joins Ruby, Node.js, Haskell, Perl, Go-almost every other contemporary language with a majority open-source community. Thank you, Python.

If you do find that pip is not available when using Python 3.4+ or Python 2.7.9+, simply execute e.g.:

py -3 -m ensurepip

Of course, that doesn't mean Python packaging is problem solved. The experience remains frustrating. I discuss this in the Stack Overflow question Does Python have a package/module management system?.

And, alas for everyone using Python 2.7.8 or earlier (a sizable portion of the community). There's no plan to ship Pip to you. Manual instructions follow.

Python 2 = 2.7.8 and Python 3 = 3.3

Flying in the face of its 'batteries included' motto, Python ships without a package manager. To make matters worse, Pip was-until recently-ironically difficult to install.

Official instructions

Per https://pip.pypa.io/en/stable/installing/#do-i-need-to-install-pip:

Download get-pip.py, being careful to save it as a .py file rather than .txt. Then, run it from the command prompt:

python get-pip.py

You possibly need an administrator command prompt to do this. Follow Start a Command Prompt as an Administrator (Microsoft TechNet).

This installs the pip package, which (in Windows) contains ...\Scripts\pip.exe that path must be in PATH environment variable to use pip from the command line (see the second part of 'Alternative Instructions' for adding it to your PATH,

Alternative instructions

The official documentation tells users to install Pip and each of its dependencies from source. That's tedious for the experienced and prohibitively difficult for newbies.

For our sake, Christoph Gohlke prepares Windows installers (.msi) for popular Python packages. He builds installers for all Python versions, both 32 and 64 bit. You need to:

  1. Install setuptools
  2. Install pip

For me, this installed Pip at C:\Python27\Scripts\pip.exe. Find pip.exe on your computer, then add its folder (for example, C:\Python27\Scripts) to your path (Start / Edit environment variables). Now you should be able to run pip from the command line. Try installing a package:

pip install httpie

There you go (hopefully)! Solutions for common problems are given below:

Proxy problems

If you work in an office, you might be behind an HTTP proxy. If so, set the environment variables http_proxy and https_proxy. Most Python applications (and other free software) respect these. Example syntax:

http://proxy_url:port
http://username:[email protected]_url:port

If you're really unlucky, your proxy might be a Microsoft NTLM proxy. Free software can't cope. The only solution is to install a free software friendly proxy that forwards to the nasty proxy. http://cntlm.sourceforge.net/

Unable to find vcvarsall.bat

Python modules can be partly written in C or C++. Pip tries to compile from source. If you don't have a C/C++ compiler installed and configured, you'll see this cryptic error message.

Error: Unable to find vcvarsall.bat

You can fix that by installing a C++ compiler such as MinGW or Visual C++. Microsoft actually ships one specifically for use with Python. Or try Microsoft Visual C++ Compiler for Python 2.7.

Often though it's easier to check Christoph's site for your package.

Ref: https://bit.ly/2B0ch3y