Appendix A — Keyword and Function Reference

A.1 Built-in Keywords

The following table provide a complete list of the built-in keywords in Python. An online version with clickable definitions is available here.

Table A.1: The built-in keywords in Python and what they do
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
finally Used with exceptions, will be executed no matter what occurs
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
try To make a try…except statement
while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator

A.2 Built-in Functions

The following table provides a comprehensive list of the built-in function included in Python. An online version of this list with clickable definitions to the functions is available here.

Table A.2: The built-in functions in Python and what they do
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are True
any() Returns True if any item in an iterable object is True
ascii() Returns a readable version of an object
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (dict)
dir() Returns a list of the specified object’s properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the dict property of an object
zip() Returns an iterator, from two or more iterators

A.3 list Methods

A full list of methods with clickable definitions can be found here.

Table A.3: List of methods on a list object
Method Description
append Adds a new item to the end itself
clear Deletes all items from itself
copy Returns a copy of itself
count Returns the number of times the given value occurs itself
extend Joins another list to the end of itself
index Retuns the first location of the given value
insert Writes the given value to the given location
pop Removes the item at the given address and returns it
remove Removes the first occurance of the given value
reverse Reverse the order of itself
sort Sorts the values in place

A.4 dict Methods

A detailed tutorial on using dictionaries (dicts) can be found on the RealPython website. A full list of methods with clickable definitions can be found here.

Table A.4: List of methods on a dict object
Method Description
clear Removes all the elements from the dictionary
copy Returns a copy of the dictionary
fromkeys Returns a dictionary with the specified keys and value
get Returns the value of the specified key
items Returns a list containing a tuple for each key value pair
keys Returns a list containing the dictionary’s keys
pop Removes the element with the specified key
popitem Removes the last inserted key-value pair
setdefault Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update Updates the dictionary with the specified key-value pairs
values Returns a list of all the values in the dictionary

A.5 set Methods

The following methods are available on set objects. A detailed tutorial of using sets can be found here.

Table A.5: List of methods on a set object
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() Inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others

A.6 str Methods

Table A.6: List of methods attached to a str object
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns True if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns True if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

A.7 file Methods

The following list gives the various methods which are attached to a file object. An online version of this list with clickable definitions to the functions is available here.

Table A.7: List of methods attached to a file object
Method Description
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating system’s perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file

A.8 DataFrame Methods

For a full interactive list see the W3 Schools Page

Table A.8
Method Description
abs Return a DataFrame with the absolute value of each value
add Adds the values of a DataFrame with the specified value(s)
add_prefix Prefix all labels
add_suffix Suffix all labels
agg Apply a function or a function name to one of the axis of the DataFrame
aggregate Apply a function or a function name to one of the axis of the DataFrame
align Aligns two DataFrames with a specified join method
all Return True if all values in the DataFrame are True, otherwise False
any Returns True if any of the values in the DataFrame are True, otherwise False
append Append new columns
applymap Execute a function for each element in the DataFrame
apply Apply a function to one of the axis of the DataFrame
assign Assign new columns
astype Convert the DataFrame into a specified dtype
at Get or set the value of the item with the specified label
axes Returns the labels of the rows and the columns of the DataFrame
bfill Replaces NULL values with the value from the next row
bool Returns the Boolean value of the DataFrame
columns Returns the column labels of the DataFrame
combine Compare the values in two DataFrames, and let a function decide which values to keep
combine_first Compare two DataFrames, and if the first DataFrame has a NULL value, it will be filled with the respective value from the second DataFrame
compare Compare two DataFrames and return the differences
convert_dtypes Converts the columns in the DataFrame into new dtypes
corr Find the correlation (relationship) between each column
count Returns the number of not empty cells for each column/row
cov Find the covariance of the columns
copy Returns a copy of the DataFrame
cummax Calculate the cumulative maximum values of the DataFrame
cummin Calculate the cumulative minmum values of the DataFrame
cumprod Calculate the cumulative product over the DataFrame
cumsum Calculate the cumulative sum over the DataFrame
describe Returns a description summary for each column in the DataFrame
diff Calculate the difference between a value and the value of the same column in the previous row
div Divides the values of a DataFrame with the specified value(s)
dot Multiplies the values of a DataFrame with values from another array-like object, and add the result
drop Drops the specified rows/columns from the DataFrame
drop_duplicates Drops duplicate values from the DataFrame
droplevel Drops the specified index/column(s)
dropna Drops all rows that contains NULL values
dtypes Returns the dtypes of the columns of the DataFrame
duplicated Returns True for duplicated rows, otherwise False
empty Returns True if the DataFrame is empty, otherwise False
eq Returns True for values that are equal to the specified value(s), otherwise False
equals Returns True if two DataFrames are equal, otherwise False
eval Evaluate a specified string
explode Converts each element into a row
ffill Replaces NULL values with the value from the previous row
fillna Replaces NULL values with the specified value
filter Filter the DataFrame according to the specified filter
first Returns the first rows of a specified date selection
floordiv Divides the values of a DataFrame with the specified value(s), and floor the values
ge Returns True for values greater than, or equal to the specified value(s), otherwise False
get Returns the item of the specified key
groupby Groups the rows/columns into specified groups
gt Returns True for values greater than the specified value(s), otherwise False
head Returns the header row and the first 5 rows, or the specified number of rows
iat Get or set the value of the item in the specified position
idxmax Returns the label of the max value in the specified axis
idxmin Returns the label of the min value in the specified axis
iloc Get or set the values of a group of elements in the specified positions
index Returns the row labels of the DataFrame
infer_objects Change the dtype of the columns in the DataFrame
info Prints information about the DataFrame
insert Insert a column in the DataFrame
interpolate Replaces not-a-number values with the interpolated method
isin Returns True if each elements in the DataFrame is in the specified value
isna Finds not-a-number values
isnull Finds NULL values
items Iterate over the columns of the DataFrame
iteritems Iterate over the columns of the DataFrame
iterrows Iterate over the rows of the DataFrame
itertuples Iterate over the rows as named tuples
join Join columns of another DataFrame
last Returns the last rows of a specified date selection
le Returns True for values less than, or equal to the specified value(s), otherwise False
loc Get or set the value of a group of elements specified using their labels
lt Returns True for values less than the specified value(s), otherwise False
keys Returns the keys of the info axis
kurtosis Returns the kurtosis of the values in the specified axis
mask Replace all values where the specified condition is True
max Return the max of the values in the specified axis
mean Return the mean of the values in the specified axis
median Return the median of the values in the specified axis
melt Reshape the DataFrame from a wide table to a long table
memory_usage Returns the memory usage of each column
merge Merge DataFrame objects
min Returns the min of the values in the specified axis
mod Modules (find the remainder) of the values of a DataFrame
mode Returns the mode of the values in the specified axis
mul Multiplies the values of a DataFrame with the specified value(s)
ndim Returns the number of dimensions of the DataFrame
ne Returns True for values that are not equal to the specified value(s), otherwise False
nlargest Sort the DataFrame by the specified columns, descending, and return the specified number of rows
notna Finds values that are not not-a-number
notnull Finds values that are not NULL
nsmallest Sort the DataFrame by the specified columns, ascending, and return the specified number of rows
nunique Returns the number of unique values in the specified axis
pct_change Returns the percentage change between the previous and the current value
pipe Apply a function to the DataFrame
pivot Re-shape the DataFrame
pivot_table Create a spreadsheet pivot table as a DataFrame
pop Removes an element from the DataFrame
pow Raise the values of one DataFrame to the values of another DataFrame
prod Returns the product of all values in the specified axis
product Returns the product of the values in the specified axis
quantile Returns the values at the specified quantile of the specified axis
query Query the DataFrame
radd Reverse-adds the values of one DataFrame with the values of another DataFrame
rdiv Reverse-divides the values of one DataFrame with the values of another DataFrame
reindex Change the labels of the DataFrame
rename Change the labels of the axes
rename_axis Change the name of the axis
reorder_levels Re-order the index levels
replace Replace the specified values
reset_index Reset the index
rfloordiv Reverse-divides the values of one DataFrame with the values of another DataFrame
rmod Reverse-modules the values of one DataFrame to the values of another DataFrame
rmul Reverse-multiplies the values of one DataFrame with the values of another DataFrame
round Returns a DataFrame with all values rounded into the specified format
rpow Reverse-raises the values of one DataFrame up to the values of another DataFrame
rsub Reverse-subtracts the values of one DataFrame to the values of another DataFrame
rtruediv Reverse-divides the values of one DataFrame with the values of another DataFrame
sample Returns a random selection elements
sem Returns the standard error of the mean in the specified axis
select_dtypes Returns a DataFrame with columns of selected data types
shape Returns the number of rows and columns of the DataFrame
set_axis Sets the index of the specified axis
set_flags Returns a new DataFrame with the specified flags
set_index Set the Index of the DataFrame
size Returns the number of elements in the DataFrame
skew Returns the skew of the values in the specified axis
sort_index Sorts the DataFrame according to the labels
sort_values Sorts the DataFrame according to the values
squeeze Converts a single column DataFrame into a Series
stack Reshape the DataFrame from a wide table to a long table
std Returns the standard deviation of the values in the specified axis
sum Returns the sum of the values in the specified axis
sub Subtracts the values of a DataFrame with the specified value(s)
swaplevel Swaps the two specified levels
T Turns rows into columns and columns into rows
tail Returns the headers and the last rows
take Returns the specified elements
to_xarray Returns an xarray object
transform Execute a function for each value in the DataFrame
transpose Turns rows into columns and columns into rows
truediv Divides the values of a DataFrame with the specified value(s)
truncate Removes elements outside of a specified set of values
update Update one DataFrame with the values from another DataFrame
value_counts Returns the number of unique rows
values Returns the DataFrame as a NumPy array
var Returns the variance of the values in the specified axis
where Replace all values where the specified condition is False
xs Returns the cross-section of the DataFrame

A.9 Numpy Reference

A.9.1 Numpy Data Types

Table A.9
Type Description
bool_ Boolean (True or False) stored as a byte
int_ Default integer type (same as C long; normally either int64 or int32)
intc Identical to C int (normally int32 or int64)
intp Integer used for indexing (same as C ssize_t; normally either int32 or int64)
int8 Byte (-128 to 127)
int16 Integer (-32768 to 32767)
int32 Integer (-2147483648 to 2147483647)
int64 Integer (-9223372036854775808 to 9223372036854775807)
uint8 Unsigned integer (0 to 255)
uint16 Unsigned integer (0 to 65535)
uint32 Unsigned integer (0 to 4294967295)
uint64 Unsigned integer (0 to 18446744073709551615)
float_ Shorthand for float64.
float16 Half precision float: sign bit, 5 bits exponent, 10 bits mantissa
float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa
float64 Double precision float: sign bit, 11 bits exponent, 52 bits mantissa
complex_ Shorthand for complex128.
complex64 Complex number, represented by two 32-bit floats
complex128 Complex number, represented by two 64-bit floats

A.9.2 Numpy ufuncs

Table A.10: List of ufunc which perform standard mathematical operations
ufunc and signature Description
add(x1, x2, /[, out, where, casting, order, …]) Add arguments element-wise.
subtract(x1, x2, /[, out, where, casting, …]) Subtract arguments, element-wise.
multiply(x1, x2, /[, out, where, casting, …]) Multiply arguments element-wise.
matmul(x1, x2, /[, out, casting, order, …]) Matrix product of two arrays.
divide(x1, x2, /[, out, where, casting, …]) Divide arguments element-wise.
logaddexp(x1, x2, /[, out, where, casting, …]) Logarithm of the sum of exponentiations of the inputs.
logaddexp2(x1, x2, /[, out, where, casting, …]) Logarithm of the sum of exponentiations of the inputs in base-2.
true_divide(x1, x2, /[, out, where, …]) Divide arguments element-wise.
floor_divide(x1, x2, /[, out, where, …]) Return the largest integer smaller or equal to the division of the inputs.
negative(x, /[, out, where, casting, order, …]) Numerical negative, element-wise.
positive(x, /[, out, where, casting, order, …]) Numerical positive, element-wise.
power(x1, x2, /[, out, where, casting, …]) First array elements raised to powers from second array, element-wise.
float_power(x1, x2, /[, out, where, …]) First array elements raised to powers from second array, element-wise.
remainder(x1, x2, /[, out, where, casting, …]) Returns the element-wise remainder of division.
mod(x1, x2, /[, out, where, casting, order, …]) Returns the element-wise remainder of division.
fmod(x1, x2, /[, out, where, casting, …]) Returns the element-wise remainder of division.
divmod(x1, x2[, out1, out2], / [, out, …]) Return element-wise quotient and remainder simultaneously.
absolute(x, /[, out, where, casting, order, …]) Calculate the absolute value element-wise.
fabs(x, /[, out, where, casting, order, …]) Compute the absolute values element-wise.
rint(x, /[, out, where, casting, order, …]) Round elements of the array to the nearest integer.
sign(x, /[, out, where, casting, order, …]) Returns an element-wise indication of the sign of a number.
heaviside(x1, x2, /[, out, where, casting, …]) Compute the Heaviside step function.
conj(x, /[, out, where, casting, order, …]) Return the complex conjugate, element-wise.
conjugate(x, /[, out, where, casting, …]) Return the complex conjugate, element-wise.
exp(x, /[, out, where, casting, order, …]) Calculate the exponential of all elements in the input array.
exp2(x, /[, out, where, casting, order, …]) Calculate 2**p for all p in the input array.
log(x, /[, out, where, casting, order, …]) Natural logarithm, element-wise.
log2(x, /[, out, where, casting, order, …]) Base-2 logarithm of x.
log10(x, /[, out, where, casting, order, …]) Return the base 10 logarithm of the input array, element-wise.
expm1(x, /[, out, where, casting, order, …]) Calculate exp(x) - 1 for all elements in the array.
log1p(x, /[, out, where, casting, order, …]) Return the natural logarithm of one plus the input array, element-wise.
sqrt(x, /[, out, where, casting, order, …]) Return the non-negative square-root of an array, element-wise.
square(x, /[, out, where, casting, order, …]) Return the element-wise square of the input.
cbrt(x, /[, out, where, casting, order, …]) Return the cube-root of an array, element-wise.
reciprocal(x, /[, out, where, casting, …]) Return the reciprocal of the argument, element-wise.
gcd(x1, x2, /[, out, where, casting, order, …]) Returns the greatest common divisor of |x1| and |x2|
lcm(x1, x2, /[, out, where, casting, order, …]) Returns the lowest common multiple of |x1| and |x2|
Table A.11: List of ufuncs which perform boolean operations
ufunc and signature Description
greater(x1, x2, /[, out, where, casting, …]) Return the truth value of (x1 > x2) element-wise.
greater_equal(x1, x2, /[, out, where, …]) Return the truth value of (x1 >= x2) element-wise.
less(x1, x2, /[, out, where, casting, …]) Return the truth value of (x1 < x2) element-wise.
less_equal(x1, x2, /[, out, where, casting, …]) Return the truth value of (x1 <= x2) element-wise.
not_equal(x1, x2, /[, out, where, casting, …]) Return (x1 != x2) element-wise.
equal(x1, x2, /[, out, where, casting, …]) Return (x1 == x2) element-wise.
logical_and(x1, x2, /[, out, where, …]) Compute the truth value of x1 AND x2 element-wise.
logical_or(x1, x2, /[, out, where, casting, …]) Compute the truth value of x1 OR x2 element-wise.
logical_xor(x1, x2, /[, out, where, …]) Compute the truth value of x1 XOR x2, element-wise.
logical_not(x, /[, out, where, casting, …]) Compute the truth value of NOT x element-wise.
maximum(x1, x2, /[, out, where, casting, …]) Element-wise maximum of array elements
minimum(x1, x2, /[, out, where, casting, …]) Element-wise minimum of array elements.
fmax(x1, x2, /[, out, where, casting, …]) Element-wise maximum of array elements.
fmin(x1, x2, /[, out, where, casting, …]) Element-wise minimum of array elements.
isfinite(x, /[, out, where, casting, order, …]) Test element-wise for finiteness (not infinity and not Not a Number).
isinf(x, /[, out, where, casting, order, …]) Test element-wise for positive or negative infinity.
isnan(x, /[, out, where, casting, order, …]) Test element-wise for NaN and return result as a boolean array.
isnat(x, /[, out, where, casting, order, …]) Test element-wise for NaT (not a time) and return result as a boolean array.
Table A.12: List of ufuncs which perform trigonometry operations
ufunc and signature Description
sin(x, /[, out, where, casting, order, …]) Trigonometric sine, element-wise.
cos(x, /[, out, where, casting, order, …]) Cosine element-wise.
tan(x, /[, out, where, casting, order, …]) Compute tangent element-wise.
arcsin(x, /[, out, where, casting, order, …]) Inverse sine, element-wise.
arccos(x, /[, out, where, casting, order, …]) Trigonometric inverse cosine, element-wise.
arctan(x, /[, out, where, casting, order, …]) Trigonometric inverse tangent, element-wise.
arctan2(x1, x2, /[, out, where, casting, …]) Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
hypot(x1, x2, /[, out, where, casting, …]) Given the “legs” of a right triangle, return its hypotenuse.
sinh(x, /[, out, where, casting, order, …]) Hyperbolic sine, element-wise.
cosh(x, /[, out, where, casting, order, …]) Hyperbolic cosine, element-wise.
tanh(x, /[, out, where, casting, order, …]) Compute hyperbolic tangent element-wise.
arcsinh(x, /[, out, where, casting, order, …]) Inverse hyperbolic sine element-wise.
arccosh(x, /[, out, where, casting, order, …]) Inverse hyperbolic cosine, element-wise.
arctanh(x, /[, out, where, casting, order, …]) Inverse hyperbolic tangent element-wise.
degrees(x, /[, out, where, casting, order, …]) Convert angles from radians to degrees.
radians(x, /[, out, where, casting, order, …]) Convert angles from degrees to radians.
deg2rad(x, /[, out, where, casting, order, …]) Convert angles from degrees to radians.
rad2deg(x, /[, out, where, casting, order, …]) Convert angles from radians to degrees.
Table A.13: List of miscillaneous ufuncs
ufunc and signature Description
fabs(x, /[, out, where, casting, order, …]) Compute the absolute values element-wise.
signbit(x, /[, out, where, casting, order, …]) Returns element-wise True where signbit is set (less than zero).
copysign(x1, x2, /[, out, where, casting, …]) Change the sign of x1 to that of x2, element-wise.
nextafter(x1, x2, /[, out, where, casting, …]) Return the next floating-point value after x1 towards x2, element-wise.
spacing(x, /[, out, where, casting, order, …]) Return the distance between x and the nearest adjacent number.
modf(x[, out1, out2], / [[, out, where, …]) Return the fractional and integral parts of an array, element-wise.
ldexp(x1, x2, /[, out, where, casting, …]) Returns x1 * 2**x2, element-wise.
frexp(x[, out1, out2], / [[, out, where, …]) Decompose the elements of x into mantissa and twos exponent.
fmod(x1, x2, /[, out, where, casting, …]) Returns the element-wise remainder of division.
floor(x, /[, out, where, casting, order, …]) Return the floor of the input, element-wise.
ceil(x, /[, out, where, casting, order, …]) Return the ceiling of the input, element-wise.
trunc(x, /[, out, where, casting, order, …]) Return the truncated value of the input, element-wise

A.9.3 ndarray Attributes and Methods

Table A.14: Attributes that describe details about the memory layout of the data
Attribute Description
ndarray.flags Information about the memory layout of the array.
ndarray.shape Tuple of array dimensions.
ndarray.strides Tuple of bytes to step in each dimension when traversing an array.
ndarray.ndim Number of array dimensions.
ndarray.data Python buffer object pointing to the start of the array’s data.
ndarray.size Number of elements in the array.
ndarray.itemsize Length of one array element in bytes.
ndarray.nbytes Total bytes consumed by the elements of the array.
ndarray.base Base object if memory is from some other object.
Table A.15: Attributes describing details of the data stored in the array
Attribute Description
ndarray.dtype Data-type of the array’s elements.
ndarray.T View of the transposed array.
ndarray.real The real part of the array.
ndarray.imag The imaginary part of the array.
ndarray.flat A 1-D iterator over the array.
Table A.16: Methods for converting data within the array
Method Description
ndarray.item(*args) Copy an element of an array to a standard Python scalar and return it.
ndarray.tolist() Return the array as an a.ndim-levels deep nested list of Python scalars.
ndarray.tobytes([order]) Construct Python bytes containing the raw data bytes in the array.
ndarray.tofile(fid, /[, sep, format]) Write array to a file as text or binary (default).
ndarray.dump(file) Dump a pickle of the array to the specified file.
ndarray.dumps() Returns the pickle of the array as a string.
ndarray.astype(dtype[, order, casting, …]) Copy of the array, cast to a specified type.
ndarray.byteswap([inplace]) Swap the bytes of the array elements
ndarray.copy([order]) Return a copy of the array.
ndarray.view([dtype][, type]) New view of array with the same data.
ndarray.getfield(dtype[, offset]) Returns a field of the given array as a certain type.
ndarray.setflags([write, align, uic]) Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.
ndarray.fill(value) Fill the array with a scalar value.
Table A.17: Methods for manipulating the shape of the array
Method Description
ndarray.reshape(a.reshape) Returns an array containing the same data with a new shape.
ndarray.resize(a.resize) Change shape and size of array in-place.
ndarray.transpose(*axes) Returns a view of the array with axes transposed.
ndarray.swapaxes(axis1, axis2, /) Return a view of the array with axis1 and axis2 interchanged.
ndarray.flatten([order]) Return a copy of the array collapsed into one dimension.
ndarray.ravel([order]) Return a flattened array.
ndarray.squeeze([axis]) Remove axes of length one from a.
Table A.18: Methods for selecting and manipulating data within the array
Method Description
ndarray.take(indices[, axis, out, mode]) Return an array formed from the elements of a at the given indices.
ndarray.put(indices, values[, mode]) Set a.flat[n] = values[n] for all n in indices.
ndarray.repeat(repeats[, axis]) Repeat elements of an array.
ndarray.choose(choices[, out, mode]) Use an index array to construct a new array from a set of choices.
ndarray.sort([axis, kind, order, stable, …]) Sort an array in-place.
ndarray.argsort([axis, kind, order, stable, …]) Returns the indices that would sort this array.
ndarray.partition(kth[, axis, kind, order, …]) Partially sorts the array in such a way that the value of the element in the k-th position is in the position it would be in a sorted array.
ndarray.argpartition(kth[, axis, kind, …]) Returns the indices that would partition this array.
ndarray.searchsorted(v[, side, sorter]) Find indices where elements of v should be inserted in a to maintain order.
ndarray.nonzero() Return the indices of the elements that are non-zero.
ndarray.compress(condition[, axis, out]) Return selected slices of this array along given axis.
ndarray.diagonal([offset, axis1, axis2]) Return specified diagonals.
Table A.19: Methods that perform calculations on the data within the array
Method Description
ndarray.max([axis, out, keepdims, initial, …]) Return the maximum along a given axis.
ndarray.argmax([axis, out, keepdims]) Return indices of the maximum values along the given axis.
ndarray.min([axis, out, keepdims, initial, …]) Return the minimum along a given axis.
ndarray.argmin([axis, out, keepdims]) Return indices of the minimum values along the given axis.
ndarray.clip([min, max, out]) Return an array whose values are limited to [min, max].
ndarray.conj() Complex-conjugate all elements.
ndarray.round([decimals, out]) Return a with each element rounded to the given number of decimals.
ndarray.trace([offset, axis1, axis2, dtype, out]) Return the sum along diagonals of the array.
ndarray.sum([axis, dtype, out, keepdims, …]) Return the sum of the array elements over the given axis.
ndarray.cumsum([axis, dtype, out]) Return the cumulative sum of the elements along the given axis.
ndarray.mean([axis, dtype, out, keepdims, where]) Returns the average of the array elements along given axis.
ndarray.var([axis, dtype, out, ddof, …]) Returns the variance of the array elements, along given axis.
ndarray.std([axis, dtype, out, ddof, …]) Returns the standard deviation of the array elements along given axis.
ndarray.prod([axis, dtype, out, keepdims, …]) Return the product of the array elements over the given axis
ndarray.cumprod([axis, dtype, out]) Return the cumulative product of the elements along the given axis.
ndarray.all([axis, out, keepdims, where]) Returns True if all elements evaluate to True.
ndarray.any([axis, out, keepdims, where]) Returns True if any of the elements of a evaluate to True.