How to reverse an array
This section covers [Link]()
NumPy’s [Link]() function allows you to flip, or reverse, the contents of an
array along an axis. When using [Link](), specify the array you would like
to reverse and the axis. If you don’t specify the axis, NumPy will reverse
the contents along all of the axes of your input array.
Reversing a 1D array
If you begin with a 1D array like this one:
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8])
You can reverse it with:
reversed_arr = [Link](arr)
If you want to print your reversed array, you can run:
print('Reversed Array: ', reversed_arr)
Reversed Array: [8 7 6 5 4 3 2 1]
Reversing a 2D array
A 2D array works much the same way.
If you start with this array:
arr_2d = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
You can reverse the content in all of the rows and all of the columns with:
reversed_arr = [Link](arr_2d)
print(reversed_arr)
[[12 11 10 9]
[ 8 7 6 5]
[ 4 3 2 1]]
You can easily reverse only the rows with:
reversed_arr_rows = [Link](arr_2d, axis=0)
print(reversed_arr_rows)
[[ 9 10 11 12]
[ 5 6 7 8]
[ 1 2 3 4]]
Or reverse only the columns with:
reversed_arr_columns = [Link](arr_2d, axis=1)
print(reversed_arr_columns)
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]]
You can also reverse the contents of only one column or row. For example,
you can reverse the contents of the row at index position 1 (the second
row):
arr_2d[1] = [Link](arr_2d[1])
print(arr_2d)
[[ 1 2 3 4]
[ 8 7 6 5]
[ 9 10 11 12]]
You can also reverse the column at index position 1 (the second column):
arr_2d[:,1] = [Link](arr_2d[:,1])
print(arr_2d)
[[ 1 10 3 4]
[ 8 7 6 5]
[ 9 2 11 12]]
Read more about reversing arrays at flip.
Reshaping and flattening multidimensional arrays
This section covers .flatten(), ravel()
There are two popular ways to flatten an array: .flatten() and .ravel(). The
primary difference between the two is that the new array created
using ravel() is actually a reference to the parent array (i.e., a “view”).
This means that any changes to the new array will affect the parent array
as well. Since ravel does not create a copy, it’s memory efficient.
If you start with this array:
x = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
You can use flatten to flatten your array into a 1D array.
[Link]()
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
When you use flatten, changes to your new array won’t change the parent
array.
For example:
a1 = [Link]()
a1[0] = 99
print(x) # Original array
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
print(a1) # New array
[99 2 3 4 5 6 7 8 9 10 11 12]
But when you use ravel, the changes you make to the new array will affect
the parent array.
For example:
a2 = [Link]()
a2[0] = 98
print(x) # Original array
[[98 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
print(a2) # New array
[98 2 3 4 5 6 7 8 9 10 11 12]
Read more about flatten at [Link] and ravel at ravel.
How to access the docstring for more information
This section covers help(), ?, ??
When it comes to the data science ecosystem, Python and NumPy are
built with the user in mind. One of the best examples of this is the built-in
access to documentation. Every object contains the reference to a string,
which is known as the docstring. In most cases, this docstring contains a
quick and concise summary of the object and how to use it. Python has a
built-in help() function that can help you access this information. This
means that nearly any time you need more information, you can
use help() to quickly find the information that you need.
For example:
help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
Because access to additional information is so useful, IPython uses
the ? character as a shorthand for accessing this documentation along
with other relevant information. IPython is a command shell for interactive
computing in multiple languages. You can find more information about
IPython here.
For example:
max?
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
Type: builtin_function_or_method
You can even use this notation for object methods and objects
themselves.
Let’s say you create this array:
a = [Link]([1, 2, 3, 4, 5, 6])
Then you can obtain a lot of useful information (first details about a itself,
followed by the docstring of ndarray of which a is an instance):
a?
Type: ndarray
String form: [1 2 3 4 5 6]
Length: 6
File: ~/anaconda3/lib/python3.9/site-packages/numpy/__init__.py
Docstring: <no docstring>
Class docstring:
ndarray(shape, dtype=float, buffer=None, offset=0,
strides=None, order=None)
An array object represents a multidimensional, homogeneous array
of fixed-size items. An associated data-type object describes the
format of each element in the array (its byte-order, how many bytes it
occupies in memory, whether it is an integer, a floating point number,
or something else, etc.)
Arrays should be constructed using `array`, `zeros` or `empty` (refer
to the See Also section below). The parameters given here refer to
a low-level method (`ndarray(...)`) for instantiating an array.
For more information, refer to the `numpy` module and examine the
methods and attributes of an array.
Parameters
----------
(for the __new__ method; see Notes below)
shape : tuple of ints
Shape of created array.
...
This also works for functions and other objects that you create. Just
remember to include a docstring with your function using a string literal
(""" """ or ''' ''' around your documentation).
For example, if you create this function:
def double(a):
'''Return a * 2'''
return a * 2
You can obtain information about the function:
double?
Signature: double(a)
Docstring: Return a * 2
File: ~/Desktop/<ipython-input-23-b5adf20be596>
Type: function
You can reach another level of information by reading the source code of
the object you’re interested in. Using a double question mark (??) allows
you to access the source code.
For example:
double??
Signature: double(a)
Source:
def double(a):
'''Return a * 2'''
return a * 2
File: ~/Desktop/<ipython-input-23-b5adf20be596>
Type: function
If the object in question is compiled in a language other than Python,
using ?? will return the same information as ?. You’ll find this with a lot of
built-in objects and types, for example:
len?
Signature: len(obj, /)
Docstring: Return the number of items in a container.
Type: builtin_function_or_method
and :
len??
Signature: len(obj, /)
Docstring: Return the number of items in a container.
Type: builtin_function_or_method
have the same output because they were compiled in a programming
language other than Python.