numpy.char.isnumeric   char.isnumeric(a)[source]

For each element, return True if there are only numeric characters in the element. Calls unicode.isnumeric element-wise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155,
VULGAR FRACTION ONE FIFTH.  Parameters

aarray_like, unicode

Input array.    Returns

outndarray, bool

Array of booleans of same shape as a.      See also  unicode.isnumeric


numpy.char.isspace   char.isspace(a)[source]

Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. Calls str.isspace element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like of str or unicode

  Returns

outndarray

Output array of bools      See also  str.isspace


numpy.char.istitle   char.istitle(a)[source]

Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. Call str.istitle element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like of str or unicode

  Returns

outndarray

Output array of bools      See also  str.istitle


numpy.char.isupper   char.isupper(a)[source]

Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. Call str.isupper element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like of str or unicode

  Returns

outndarray

Output array of bools      See also  str.isupper


numpy.char.join   char.join(sep, seq)[source]

Return a string which is the concatenation of the strings in the sequence seq. Calls str.join element-wise.  Parameters

separray_like of str or unicode

seqarray_like of str or unicode

  Returns

outndarray

Output array of str or unicode, depending on input types      See also  str.join


numpy.char.less   char.less(x1, x2)[source]

Return (x1 < x2) element-wise. Unlike numpy.greater, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.  Parameters

x1, x2array_like of str or unicode

Input arrays of the same shape.    Returns

outndarray

Output array of bools.      See also
equal, not_equal, greater_equal, less_equal, greater


numpy.char.less_equal   char.less_equal(x1, x2)[source]

Return (x1 <= x2) element-wise. Unlike numpy.less_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.  Parameters

x1, x2array_like of str or unicode

Input arrays of the same shape.    Returns

outndarray

Output array of bools.      See also
equal, not_equal, greater_equal, greater, less


numpy.char.ljust   char.ljust(a, width, fillchar=' ')[source]

Return an array with the elements of a left-justified in a string of length width. Calls str.ljust element-wise.  Parameters

aarray_like of str or unicode

widthint

The length of the resulting strings
fillcharstr or unicode, optional

The character to use for padding    Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.ljust


numpy.char.lower   char.lower(a)[source]

Return an array with the elements converted to lowercase. Call str.lower element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like, {str, unicode}

Input array.    Returns

outndarray, {str, unicode}

Output array of str or unicode, depending on input type      See also  str.lower
  Examples >>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
>>> np.char.lower(c)
array(['a1b c', '1bca', 'bca1'], dtype='<U5')


numpy.char.lstrip   char.lstrip(a, chars=None)[source]

For each element in a, return a copy with the leading characters removed. Calls str.lstrip element-wise.  Parameters

aarray-like, {str, unicode}

Input array.
chars{str, unicode}, optional

The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped.    Returns

outndarray, {str, unicode}

Output array of str or unicode, depending on input type      See also  str.lstrip
  Examples >>> c = np.array(['aAaAaA', '  aA  ', 'abBABba'])
>>> c
array(['aAaAaA', '  aA  ', 'abBABba'], dtype='<U7')
 The ‘a’ variable is unstripped from c[1] because whitespace leading. >>> np.char.lstrip(c, 'a')
array(['AaAaA', '  aA  ', 'bBABba'], dtype='<U7')
 >>> np.char.lstrip(c, 'A') # leaves c unchanged
array(['aAaAaA', '  aA  ', 'abBABba'], dtype='<U7')
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, '')).all()
... # XXX: is this a regression? This used to return True
... # np.char.lstrip(c,'') does not modify c at all.
False
>>> (np.char.lstrip(c, ' ') == np.char.lstrip(c, None)).all()
True


numpy.char.mod   char.mod(a, values)[source]

Return (a % i), that is pre-Python 2.6 string formatting (interpolation), element-wise for a pair of array_likes of str or unicode.  Parameters

aarray_like of str or unicode

valuesarray_like of values

These values will be element-wise interpolated into the string.    Returns

outndarray

Output array of str or unicode, depending on input types      See also  str.__mod__


numpy.char.multiply   char.multiply(a, i)[source]

Return (a * i), that is string multiple concatenation, element-wise. Values in i of less than 0 are treated as 0 (which yields an empty string).  Parameters

aarray_like of str or unicode

iarray_like of ints

  Returns

outndarray

Output array of str or unicode, depending on input types


numpy.char.not_equal   char.not_equal(x1, x2)[source]

Return (x1 != x2) element-wise. Unlike numpy.not_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.  Parameters

x1, x2array_like of str or unicode

Input arrays of the same shape.    Returns

outndarray

Output array of bools.      See also
equal, greater_equal, less_equal, greater, less


numpy.char.partition   char.partition(a, sep)[source]

Partition each element in a around sep. Calls str.partition element-wise. For each element in a, split the element as the first occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings.  Parameters

aarray_like, {str, unicode}

Input array
sep{str, unicode}

Separator to split each string element in a.    Returns

outndarray, {str, unicode}

Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element.      See also  str.partition


numpy.char.replace   char.replace(a, old, new, count=None)[source]

For each element in a, return a copy of the string with all occurrences of substring old replaced by new. Calls str.replace element-wise.  Parameters

aarray-like of str or unicode

old, newstr or unicode

countint, optional

If the optional argument count is given, only the first count occurrences are replaced.    Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.replace


numpy.char.rfind   char.rfind(a, sub, start=0, end=None)[source]

For each element in a, return the highest index in the string where substring sub is found, such that sub is contained within [start, end]. Calls str.rfind element-wise.  Parameters

aarray-like of str or unicode

substr or unicode

start, endint, optional

Optional arguments start and end are interpreted as in slice notation.    Returns

outndarray

Output array of ints. Return -1 on failure.      See also  str.rfind


numpy.char.rindex   char.rindex(a, sub, start=0, end=None)[source]

Like rfind, but raises ValueError when the substring sub is not found. Calls str.rindex element-wise.  Parameters

aarray-like of str or unicode

substr or unicode

start, endint, optional

  Returns

outndarray

Output array of ints.      See also
rfind, str.rindex


numpy.char.rjust   char.rjust(a, width, fillchar=' ')[source]

Return an array with the elements of a right-justified in a string of length width. Calls str.rjust element-wise.  Parameters

aarray_like of str or unicode

widthint

The length of the resulting strings
fillcharstr or unicode, optional

The character to use for padding    Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.rjust


numpy.char.rpartition   char.rpartition(a, sep)[source]

Partition (split) each element around the right-most separator. Calls str.rpartition element-wise. For each element in a, split the element as the last occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings.  Parameters

aarray_like of str or unicode

Input array
sepstr or unicode

Right-most separator to split each element in array.    Returns

outndarray

Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element.      See also  str.rpartition


numpy.char.rsplit   char.rsplit(a, sep=None, maxsplit=None)[source]

For each element in a, return a list of the words in the string, using sep as the delimiter string. Calls str.rsplit element-wise. Except for splitting from the right, rsplit behaves like split.  Parameters

aarray_like of str or unicode

sepstr or unicode, optional

If sep is not specified or None, any whitespace string is a separator.
maxsplitint, optional

If maxsplit is given, at most maxsplit splits are done, the rightmost ones.    Returns

outndarray

Array of list objects      See also
str.rsplit, split


numpy.char.rstrip   char.rstrip(a, chars=None)[source]

For each element in a, return a copy with the trailing characters removed. Calls str.rstrip element-wise.  Parameters

aarray-like of str or unicode

charsstr or unicode, optional

The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped.    Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.rstrip
  Examples >>> c = np.array(['aAaAaA', 'abBABba'], dtype='S7'); c
array(['aAaAaA', 'abBABba'],
    dtype='|S7')
>>> np.char.rstrip(c, b'a')
array(['aAaAaA', 'abBABb'],
    dtype='|S7')
>>> np.char.rstrip(c, b'A')
array(['aAaAa', 'abBABba'],
    dtype='|S7')


numpy.char.split   char.split(a, sep=None, maxsplit=None)[source]

For each element in a, return a list of the words in the string, using sep as the delimiter string. Calls str.split element-wise.  Parameters

aarray_like of str or unicode

sepstr or unicode, optional

If sep is not specified or None, any whitespace string is a separator.
maxsplitint, optional

If maxsplit is given, at most maxsplit splits are done.    Returns

outndarray

Array of list objects      See also
str.split, rsplit


numpy.char.splitlines   char.splitlines(a, keepends=None)[source]

For each element in a, return a list of the lines in the element, breaking at line boundaries. Calls str.splitlines element-wise.  Parameters

aarray_like of str or unicode

keependsbool, optional

Line breaks are not included in the resulting list unless keepends is given and true.    Returns

outndarray

Array of list objects      See also  str.splitlines


numpy.char.startswith   char.startswith(a, prefix, start=0, end=None)[source]

Returns a boolean array which is True where the string element in a starts with prefix, otherwise False. Calls str.startswith element-wise.  Parameters

aarray_like of str or unicode

prefixstr

start, endint, optional

With optional start, test beginning at that position. With optional end, stop comparing at that position.    Returns

outndarray

Array of booleans      See also  str.startswith


numpy.char.str_len   char.str_len(a)[source]

Return len(a) element-wise.  Parameters

aarray_like of str or unicode

  Returns

outndarray

Output array of integers      See also  builtins.len


numpy.char.strip   char.strip(a, chars=None)[source]

For each element in a, return a copy with the leading and trailing characters removed. Calls str.strip element-wise.  Parameters

aarray-like of str or unicode

charsstr or unicode, optional

The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.    Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.strip
  Examples >>> c = np.array(['aAaAaA', '  aA  ', 'abBABba'])
>>> c
array(['aAaAaA', '  aA  ', 'abBABba'], dtype='<U7')
>>> np.char.strip(c)
array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
>>> np.char.strip(c, 'a') # 'a' unstripped from c[1] because whitespace leads
array(['AaAaA', '  aA  ', 'bBABb'], dtype='<U7')
>>> np.char.strip(c, 'A') # 'A' unstripped from c[1] because (unprinted) ws trails
array(['aAaAa', '  aA  ', 'abBABba'], dtype='<U7')


numpy.char.swapcase   char.swapcase(a)[source]

Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa. Calls str.swapcase element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like, {str, unicode}

Input array.    Returns

outndarray, {str, unicode}

Output array of str or unicode, depending on input type      See also  str.swapcase
  Examples >>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
    dtype='|S5')
>>> np.char.swapcase(c)
array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
    dtype='|S5')


numpy.char.title   char.title(a)[source]

Return element-wise title cased version of string or unicode. Title case words start with uppercase characters, all remaining cased characters are lowercase. Calls str.title element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like, {str, unicode}

Input array.    Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.title
  Examples >>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
    dtype='|S5')
>>> np.char.title(c)
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
    dtype='|S5')


numpy.char.translate   char.translate(a, table, deletechars=None)[source]

For each element in a, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table. Calls str.translate element-wise.  Parameters

aarray-like of str or unicode

tablestr of length 256

deletecharsstr

  Returns

outndarray

Output array of str or unicode, depending on input type      See also  str.translate


numpy.char.upper   char.upper(a)[source]

Return an array with the elements converted to uppercase. Calls str.upper element-wise. For 8-bit strings, this method is locale-dependent.  Parameters

aarray_like, {str, unicode}

Input array.    Returns

outndarray, {str, unicode}

Output array of str or unicode, depending on input type      See also  str.upper
  Examples >>> c = np.array(['a1b c', '1bca', 'bca1']); c
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
>>> np.char.upper(c)
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')


numpy.char.zfill   char.zfill(a, width)[source]

Return the numeric string left-filled with zeros Calls str.zfill element-wise.  Parameters

aarray_like, {str, unicode}

Input array.
widthint

Width of string to left-fill elements in a.    Returns

outndarray, {str, unicode}

Output array of str or unicode, depending on input type      See also  str.zfill


numpy.chararray.argsort method   chararray.argsort(axis=- 1, kind=None, order=None)[source]

Returns the indices that would sort this array. Refer to numpy.argsort for full documentation.  See also  numpy.argsort

equivalent function


numpy.chararray.astype method   chararray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)

Copy of the array, cast to a specified type.  Parameters

dtypestr or dtype

Typecode or data-type to which the array is cast.
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.  ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done.
subokbool, optional

If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
copybool, optional

By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.    Returns

arr_tndarray

Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.    Raises
 ComplexWarning

When casting from complex to float or int. To avoid this, one should use a.real.astype(t).     Notes  Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.   Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.  Examples >>> x = np.array([1, 2, 2.5])
>>> x
array([1. ,  2. ,  2.5])
 >>> x.astype(int)
array([1, 2, 2])


numpy.chararray.base attribute   chararray.base

Base object if memory is from some other object. Examples The base of an array that owns its memory is None: >>> x = np.array([1,2,3,4])
>>> x.base is None
True
 Slicing creates a view, whose memory is shared with x: >>> y = x[2:]
>>> y.base is x
True


numpy.chararray.copy method   chararray.copy(order='C')

Return a copy of the array.  Parameters

order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and numpy.copy are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)      See also  numpy.copy

Similar function with different default behavior  numpy.copyto
  Notes This function is the preferred method for creating an array copy. The function numpy.copy is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default. Examples >>> x = np.array([[1,2,3],[4,5,6]], order='F')
 >>> y = x.copy()
 >>> x.fill(0)
 >>> x
array([[0, 0, 0],
       [0, 0, 0]])
 >>> y
array([[1, 2, 3],
       [4, 5, 6]])
 >>> y.flags['C_CONTIGUOUS']
True


numpy.chararray.count method   chararray.count(sub, start=0, end=None)[source]

Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end].  See also  char.count


numpy.chararray.ctypes attribute   chararray.ctypes

An object to simplify the interaction of the array with the ctypes module. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.  Parameters
 None
  Returns

cPython object

Possessing attributes data, shape, strides, etc.      See also  numpy.ctypeslib
  Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):   _ctypes.data

A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0]. Note that unlike data_as, a reference will not be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p)
   _ctypes.shape

(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.
   _ctypes.strides

(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
   _ctypes.data_as(obj)[source]

Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)). The returned pointer will keep a reference to the array.
   _ctypes.shape_as(obj)[source]

Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short).
   _ctypes.strides_as(obj)[source]

Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong).
 If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute. Examples >>> import ctypes
>>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
>>> x
array([[0, 1],
       [2, 3]], dtype=int32)
>>> x.ctypes.data
31962608 # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
<__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
c_uint(0)
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
c_ulong(4294967296)
>>> x.ctypes.shape
<numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
>>> x.ctypes.strides
<numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary


numpy.chararray.data attribute   chararray.data

Python buffer object pointing to the start of the array’s data.


numpy.chararray.decode method   chararray.decode(encoding=None, errors=None)[source]

Calls str.decode element-wise.  See also  char.decode


numpy.chararray.dump method   chararray.dump(file)

Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.  Parameters

filestr or Path

A string naming the dump file.  Changed in version 1.17.0: pathlib.Path objects are now accepted.


numpy.chararray.dumps method   chararray.dumps()

Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.  Parameters
 None


numpy.chararray.encode method   chararray.encode(encoding=None, errors=None)[source]

Calls str.encode element-wise.  See also  char.encode


numpy.chararray.endswith method   chararray.endswith(suffix, start=0, end=None)[source]

Returns a boolean array which is True where the string element in self ends with suffix, otherwise False.  See also  char.endswith


numpy.chararray.expandtabs method   chararray.expandtabs(tabsize=8)[source]

Return a copy of each string element where all tab characters are replaced by one or more spaces.  See also  char.expandtabs


numpy.chararray.fill method   chararray.fill(value)

Fill the array with a scalar value.  Parameters

valuescalar

All elements of a will be assigned this value.     Examples >>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([1.,  1.])


numpy.chararray.find method   chararray.find(sub, start=0, end=None)[source]

For each element, return the lowest index in the string where substring sub is found.  See also  char.find


numpy.chararray.flags attribute   chararray.flags

Information about the memory layout of the array. Notes The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access. Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags. The array flags cannot be set arbitrarily:  UPDATEIFCOPY can only be set False. WRITEBACKIFCOPY can only be set False. ALIGNED can only be set True if the data is truly aligned. WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string.  Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays. Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.  Attributes
 C_CONTIGUOUS (C)

The data is in a single, C-style contiguous segment.  F_CONTIGUOUS (F)

The data is in a single, Fortran-style contiguous segment.  OWNDATA (O)

The array owns the memory it uses or borrows it from another object.  WRITEABLE (W)

The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.  ALIGNED (A)

The data and all elements are aligned appropriately for the hardware.  WRITEBACKIFCOPY (X)

This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.  UPDATEIFCOPY (U)

(Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array.  FNC

F_CONTIGUOUS and not C_CONTIGUOUS.  FORC

F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).  BEHAVED (B)

ALIGNED and WRITEABLE.  CARRAY (CA)

BEHAVED and C_CONTIGUOUS.  FARRAY (FA)

BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.


numpy.chararray.flat attribute   chararray.flat

A 1-D iterator over the array. This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.  See also  flatten

Return a copy of the array collapsed into one dimension.  flatiter
  Examples >>> x = np.arange(1, 7).reshape(2, 3)
>>> x
array([[1, 2, 3],
       [4, 5, 6]])
>>> x.flat[3]
4
>>> x.T
array([[1, 4],
       [2, 5],
       [3, 6]])
>>> x.T.flat[3]
5
>>> type(x.flat)
<class 'numpy.flatiter'>
 An assignment example: >>> x.flat = 3; x
array([[3, 3, 3],
       [3, 3, 3]])
>>> x.flat[[1,4]] = 1; x
array([[3, 1, 3],
       [3, 1, 3]])


numpy.chararray.flatten method   chararray.flatten(order='C')

Return a copy of the array collapsed into one dimension.  Parameters

order{‘C’, ‘F’, ‘A’, ‘K’}, optional

‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.    Returns

yndarray

A copy of the input array, flattened to one dimension.      See also  ravel

Return a flattened array.  flat

A 1-D flat iterator over the array.    Examples >>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])


numpy.chararray.getfield method   chararray.getfield(dtype, offset=0)

Returns a field of the given array as a certain type. A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.  Parameters

dtypestr or dtype

The data type of the view. The dtype size of the view can not be larger than that of the array itself.
offsetint

Number of bytes to skip before beginning the element view.     Examples >>> x = np.diag([1.+1.j]*2)
>>> x[1, 1] = 2 + 4.j
>>> x
array([[1.+1.j,  0.+0.j],
       [0.+0.j,  2.+4.j]])
>>> x.getfield(np.float64)
array([[1.,  0.],
       [0.,  2.]])
 By choosing an offset of 8 bytes we can select the complex part of the array for our view: >>> x.getfield(np.float64, offset=8)
array([[1.,  0.],
       [0.,  4.]])


numpy.chararray.index method   chararray.index(sub, start=0, end=None)[source]

Like find, but raises ValueError when the substring is not found.  See also  char.index


numpy.chararray.isalnum method   chararray.isalnum()[source]

Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise.  See also  char.isalnum


numpy.chararray.isalpha method   chararray.isalpha()[source]

Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise.  See also  char.isalpha


numpy.chararray.isdecimal method   chararray.isdecimal()[source]

For each element in self, return True if there are only decimal characters in the element.  See also  char.isdecimal


numpy.chararray.isdigit method   chararray.isdigit()[source]

Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise.  See also  char.isdigit


numpy.chararray.islower method   chararray.islower()[source]

Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.  See also  char.islower


numpy.chararray.isnumeric method   chararray.isnumeric()[source]

For each element in self, return True if there are only numeric characters in the element.  See also  char.isnumeric


numpy.chararray.isspace method   chararray.isspace()[source]

Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise.  See also  char.isspace


numpy.chararray.istitle method   chararray.istitle()[source]

Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise.  See also  char.istitle


numpy.chararray.isupper method   chararray.isupper()[source]

Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise.  See also  char.isupper


numpy.chararray.item method   chararray.item(*args)

Copy an element of an array to a standard Python scalar and return it.  Parameters

*argsArguments (variable number and type)

 none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned. int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return. tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array.     Returns

zStandard Python scalar object

A copy of the specified element of the array as a suitable Python scalar     Notes When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned. item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math. Examples >>> np.random.seed(123)
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[2, 2, 6],
       [1, 3, 6],
       [1, 0, 1]])
>>> x.item(3)
1
>>> x.item(7)
0
>>> x.item((0, 1))
2
>>> x.item((2, 2))
1


numpy.chararray.itemsize attribute   chararray.itemsize

Length of one array element in bytes. Examples >>> x = np.array([1,2,3], dtype=np.float64)
>>> x.itemsize
8
>>> x = np.array([1,2,3], dtype=np.complex128)
>>> x.itemsize
16


numpy.chararray.join method   chararray.join(seq)[source]

Return a string which is the concatenation of the strings in the sequence seq.  See also  char.join


numpy.chararray.ljust method   chararray.ljust(width, fillchar=' ')[source]

Return an array with the elements of self left-justified in a string of length width.  See also  char.ljust


numpy.chararray.lower method   chararray.lower()[source]

Return an array with the elements of self converted to lowercase.  See also  char.lower


numpy.chararray.lstrip method   chararray.lstrip(chars=None)[source]

For each element in self, return a copy with the leading characters removed.  See also  char.lstrip


numpy.chararray.nbytes attribute   chararray.nbytes

Total bytes consumed by the elements of the array. Notes Does not include memory consumed by non-element attributes of the array object. Examples >>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480


numpy.chararray.ndim attribute   chararray.ndim

Number of array dimensions. Examples >>> x = np.array([1, 2, 3])
>>> x.ndim
1
>>> y = np.zeros((2, 3, 4))
>>> y.ndim
3


numpy.chararray.nonzero method   chararray.nonzero()

Return the indices of the elements that are non-zero. Refer to numpy.nonzero for full documentation.  See also  numpy.nonzero

equivalent function


numpy.chararray.put method   chararray.put(indices, values, mode='raise')

Set a.flat[n] = values[n] for all n in indices. Refer to numpy.put for full documentation.  See also  numpy.put

equivalent function


numpy.chararray.ravel method   chararray.ravel([order])

Return a flattened array. Refer to numpy.ravel for full documentation.  See also  numpy.ravel

equivalent function  ndarray.flat

a flat iterator on the array.


numpy.chararray.repeat method   chararray.repeat(repeats, axis=None)

Repeat elements of an array. Refer to numpy.repeat for full documentation.  See also  numpy.repeat

equivalent function


numpy.chararray.replace method   chararray.replace(old, new, count=None)[source]

For each element in self, return a copy of the string with all occurrences of substring old replaced by new.  See also  char.replace


numpy.chararray.reshape method   chararray.reshape(shape, order='C')

Returns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation.  See also  numpy.reshape

equivalent function    Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).


numpy.chararray.resize method   chararray.resize(new_shape, refcheck=True)

Change shape and size of array in-place.  Parameters

new_shapetuple of ints, or n ints

Shape of resized array.
refcheckbool, optional

If False, reference count will not be checked. Default is True.    Returns
 None
  Raises
 ValueError

If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist.  SystemError

If the order keyword argument is specified. This behaviour is a bug in NumPy.      See also  resize

Return a new array with the specified shape.    Notes This reallocates space for the data area if necessary. Only contiguous arrays (data elements consecutive in memory) can be resized. The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False. Examples Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped: >>> a = np.array([[0, 1], [2, 3]], order='C')
>>> a.resize((2, 1))
>>> a
array([[0],
       [1]])
 >>> a = np.array([[0, 1], [2, 3]], order='F')
>>> a.resize((2, 1))
>>> a
array([[0],
       [2]])
 Enlarging an array: as above, but missing entries are filled with zeros: >>> b = np.array([[0, 1], [2, 3]])
>>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
>>> b
array([[0, 1, 2],
       [3, 0, 0]])
 Referencing an array prevents resizing… >>> c = a
>>> a.resize((1, 1))
Traceback (most recent call last):
...
ValueError: cannot resize an array that references or is referenced ...
 Unless refcheck is False: >>> a.resize((1, 1), refcheck=False)
>>> a
array([[0]])
>>> c
array([[0]])


numpy.chararray.rfind method   chararray.rfind(sub, start=0, end=None)[source]

For each element in self, return the highest index in the string where substring sub is found, such that sub is contained within [start, end].  See also  char.rfind


numpy.chararray.rindex method   chararray.rindex(sub, start=0, end=None)[source]

Like rfind, but raises ValueError when the substring sub is not found.  See also  char.rindex


numpy.chararray.rjust method   chararray.rjust(width, fillchar=' ')[source]

Return an array with the elements of self right-justified in a string of length width.  See also  char.rjust


numpy.chararray.rsplit method   chararray.rsplit(sep=None, maxsplit=None)[source]

For each element in self, return a list of the words in the string, using sep as the delimiter string.  See also  char.rsplit


numpy.chararray.rstrip method   chararray.rstrip(chars=None)[source]

For each element in self, return a copy with the trailing characters removed.  See also  char.rstrip


numpy.chararray.searchsorted method   chararray.searchsorted(v, side='left', sorter=None)

Find indices where elements of v should be inserted in a to maintain order. For full documentation, see numpy.searchsorted  See also  numpy.searchsorted

equivalent function


numpy.chararray.setfield method   chararray.setfield(val, dtype, offset=0)

Put a value into a specified place in a field defined by a data-type. Place val into a’s field defined by dtype and beginning offset bytes into the field.  Parameters

valobject

Value to be placed in field.
dtypedtype object

Data-type of the field in which to place val.
offsetint, optional

The number of bytes into the field at which to place val.    Returns
 None
    See also  getfield
  Examples >>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
       [3, 3, 3],
       [3, 3, 3]], dtype=int32)
>>> x
array([[1.0e+000, 1.5e-323, 1.5e-323],
       [1.5e-323, 1.0e+000, 1.5e-323],
       [1.5e-323, 1.5e-323, 1.0e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]])


numpy.chararray.setflags method   chararray.setflags(write=None, align=None, uic=None)

Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)  Parameters

writebool, optional

Describes whether or not a can be written to.
alignbool, optional

Describes whether or not a is aligned properly for its type.
uicbool, optional

Describes whether or not a is a copy of another “base” array.     Notes Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED. WRITEABLE (W) the data area can be written to; ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler); UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY; WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array. All flags can be accessed using the single (upper case) letter as well as the full name. Examples >>> y = np.array([[3, 1, 7],
...               [2, 0, 0],
...               [8, 5, 9]])
>>> y
array([[3, 1, 7],
       [2, 0, 0],
       [8, 5, 9]])
>>> y.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : False
  ALIGNED : False
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot set WRITEBACKIFCOPY flag to True


numpy.chararray.size attribute   chararray.size

Number of elements in the array. Equal to np.prod(a.shape), i.e., the product of the array’s dimensions. Notes a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type. Examples >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
>>> np.prod(x.shape)
30


numpy.chararray.sort method   chararray.sort(axis=- 1, kind=None, order=None)

Sort an array in-place. Refer to numpy.sort for full documentation.  Parameters

axisint, optional

Axis along which to sort. Default is -1, which means sort along the last axis.
kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional

Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility.  Changed in version 1.15.0: The ‘stable’ option was added.
orderstr or list of str, optional

When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.      See also  numpy.sort

Return a sorted copy of an array.  numpy.argsort

Indirect sort.  numpy.lexsort

Indirect stable sort on multiple keys.  numpy.searchsorted

Find elements in sorted array.  numpy.partition

Partial sort.    Notes See numpy.sort for notes on the different sorting algorithms. Examples >>> a = np.array([[1,4], [3,1]])
>>> a.sort(axis=1)
>>> a
array([[1, 4],
       [1, 3]])
>>> a.sort(axis=0)
>>> a
array([[1, 3],
       [1, 4]])
 Use the order keyword to specify a field to use when sorting a structured array: >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
>>> a.sort(order='y')
>>> a
array([(b'c', 1), (b'a', 2)],
      dtype=[('x', 'S1'), ('y', '<i8')])


numpy.chararray.split method   chararray.split(sep=None, maxsplit=None)[source]

For each element in self, return a list of the words in the string, using sep as the delimiter string.  See also  char.split


numpy.chararray.splitlines method   chararray.splitlines(keepends=None)[source]

For each element in self, return a list of the lines in the element, breaking at line boundaries.  See also  char.splitlines


numpy.chararray.squeeze method   chararray.squeeze(axis=None)

Remove axes of length one from a. Refer to numpy.squeeze for full documentation.  See also  numpy.squeeze

equivalent function


numpy.chararray.startswith method   chararray.startswith(prefix, start=0, end=None)[source]

Returns a boolean array which is True where the string element in self starts with prefix, otherwise False.  See also  char.startswith


numpy.chararray.strides attribute   chararray.strides

Tuple of bytes to step in each dimension when traversing an array. The byte offset of element (i[0], i[1], ..., i[n]) in an array a is: offset = sum(np.array(i) * a.strides)
 A more detailed explanation of strides can be found in the “ndarray.rst” file in the NumPy reference guide.  See also  numpy.lib.stride_tricks.as_strided
  Notes Imagine an array of 32-bit integers (each 4 bytes): x = np.array([[0, 1, 2, 3, 4],
              [5, 6, 7, 8, 9]], dtype=np.int32)
 This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be (20, 4). Examples >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
>>> y
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> y.strides
(48, 16, 4)
>>> y[1,1,1]
17
>>> offset=sum(y.strides * np.array((1,1,1)))
>>> offset/y.itemsize
17
 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3,5,2,2])
>>> offset = sum(i * x.strides)
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813


numpy.chararray.strip method   chararray.strip(chars=None)[source]

For each element in self, return a copy with the leading and trailing characters removed.  See also  char.strip


numpy.chararray.swapaxes method   chararray.swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged. Refer to numpy.swapaxes for full documentation.  See also  numpy.swapaxes

equivalent function


numpy.chararray.swapcase method   chararray.swapcase()[source]

For each element in self, return a copy of the string with uppercase characters converted to lowercase and vice versa.  See also  char.swapcase


numpy.chararray.T attribute   chararray.T

The transposed array. Same as self.transpose().  See also  transpose
  Examples >>> x = np.array([[1.,2.],[3.,4.]])
>>> x
array([[ 1.,  2.],
       [ 3.,  4.]])
>>> x.T
array([[ 1.,  3.],
       [ 2.,  4.]])
>>> x = np.array([1.,2.,3.,4.])
>>> x
array([ 1.,  2.,  3.,  4.])
>>> x.T
array([ 1.,  2.,  3.,  4.])


numpy.chararray.take method   chararray.take(indices, axis=None, out=None, mode='raise')

Return an array formed from the elements of a at the given indices. Refer to numpy.take for full documentation.  See also  numpy.take

equivalent function


numpy.chararray.title method   chararray.title()[source]

For each element in self, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase.  See also  char.title


numpy.chararray.tobytes method   chararray.tobytes(order='C')

Construct Python bytes containing the raw data bytes in the array. Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.  New in version 1.9.0.   Parameters

order{‘C’, ‘F’, ‘A’}, optional

Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’.    Returns

sbytes

Python bytes exhibiting a copy of a’s raw data.     Examples >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
>>> x.tobytes()
b'\x00\x00\x01\x00\x02\x00\x03\x00'
>>> x.tobytes('C') == x.tobytes()
True
>>> x.tobytes('F')
b'\x00\x00\x02\x00\x01\x00\x03\x00'


numpy.chararray.tofile method   chararray.tofile(fid, sep='', format='%s')

Write array to a file as text or binary (default). Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile().  Parameters

fidfile or str or Path

An open file object, or a string containing a filename.  Changed in version 1.17.0: pathlib.Path objects are now accepted.
sepstr

Separator between array items for text output. If “” (empty), a binary file is written, equivalent to file.write(a.tobytes()).
formatstr

Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item.     Notes This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size. When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).


numpy.chararray.tolist method   chararray.tolist()

Return the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.  Parameters
 none
  Returns

yobject, or list of object, or list of list of object, or …

The possibly nested list of array elements.     Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2])
>>> a_list = list(a)
>>> a_list
[1, 2]
>>> type(a_list[0])
<class 'numpy.uint32'>
>>> a_tolist = a.tolist()
>>> a_tolist
[1, 2]
>>> type(a_tolist[0])
<class 'int'>
 Additionally, for a 2D array, tolist applies recursively: >>> a = np.array([[1, 2], [3, 4]])
>>> list(a)
[array([1, 2]), array([3, 4])]
>>> a.tolist()
[[1, 2], [3, 4]]
 The base case for this recursion is a 0D array: >>> a = np.array(1)
>>> list(a)
Traceback (most recent call last):
  ...
TypeError: iteration over a 0-d array
>>> a.tolist()
1


numpy.chararray.tostring method   chararray.tostring(order='C')

A compatibility alias for tobytes, with exactly the same behavior. Despite its name, it returns bytes not strs.  Deprecated since version 1.19.0.


numpy.chararray.translate method   chararray.translate(table, deletechars=None)[source]

For each element in self, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table.  See also  char.translate


numpy.chararray.transpose method   chararray.transpose(*axes)

Returns a view of the array with axes transposed. For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).  Parameters

axesNone, tuple of ints, or n ints

 None or no argument: reverses the order of the axes. tuple of ints: i in the j-th place in the tuple means a’s i-th axis becomes a.transpose()’s j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form)     Returns

outndarray

View of a, with axes suitably permuted.      See also  transpose

Equivalent function  ndarray.T

Array property returning the array transposed.  ndarray.reshape

Give a new shape to an array without changing its data.    Examples >>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> a.transpose()
array([[1, 3],
       [2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
       [2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
       [2, 4]])


numpy.chararray.upper method   chararray.upper()[source]

Return an array with the elements of self converted to uppercase.  See also  char.upper


numpy.chararray.view method   chararray.view([dtype][, type])

New view of array with the same data.  Note Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_').   Parameters

dtypedata-type or ndarray sub-class, optional

Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).
typePython type, optional

Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.     Notes a.view() is used two different ways: a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory. a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. Examples >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
 Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
>>> print(type(y))
<class 'numpy.matrix'>
 Creating a view on a structured array so it can be used in calculations >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
>>> xv = x.view(dtype=np.int8).reshape(-1,2)
>>> xv
array([[1, 2],
       [3, 4]], dtype=int8)
>>> xv.mean(0)
array([2.,  3.])
 Making changes to the view changes the underlying array >>> xv[0,1] = 20
>>> x
array([(1, 20), (3,  4)], dtype=[('a', 'i1'), ('b', 'i1')])
 Using a view to convert an array to a recarray: >>> z = x.view(np.recarray)
>>> z.a
array([1, 3], dtype=int8)
 Views share data: >>> x[0] = (9, 10)
>>> z[0]
(9, 10)
 Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.: >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16)
>>> y = x[:, 0:2]
>>> y
array([[1, 2],
       [4, 5]], dtype=int16)
>>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
Traceback (most recent call last):
    ...
ValueError: To change to a dtype of a different size, the array must be C-contiguous
>>> z = y.copy()
>>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
array([[(1, 2)],
       [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])


numpy.chararray.zfill method   chararray.zfill(width)[source]

Return the numeric string left-filled with zeros in a string of length width.  See also  char.zfill


class.__array__([dtype])

If a class (ndarray subclass or not) having the __array__ method is used as the output object of an ufunc, results will not be written to the object returned by __array__. This practice will return TypeError.


class.__array_finalize__(obj)

This method is called whenever the system internally allocates a new array from obj, where obj is a subclass (subtype) of the ndarray. It can be used to change attributes of self after construction (so as to ensure a 2-d matrix for example), or to update meta-information from the “parent.” Subclasses inherit a default implementation of this method that does nothing.


class.__array_function__(func, types, args, kwargs)

 New in version 1.16.   Note  In NumPy 1.17, the protocol is enabled by default, but can be disabled with NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=0. In NumPy 1.16, you need to set the environment variable NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=1 before importing NumPy to use NumPy function overrides. Eventually, expect to __array_function__ to always be enabled.
func is an arbitrary callable exposed by NumPy’s public API, which was called in the form func(*args, **kwargs).
types is a collection collections.abc.Collection of unique argument types from the original NumPy function call that implement __array_function__. The tuple args and dict kwargs are directly passed on from the original call.  As a convenience for __array_function__ implementors, types provides all argument types with an '__array_function__' attribute. This allows implementors to quickly identify cases where they should defer to __array_function__ implementations on other arguments. Implementations should not rely on the iteration order of types. Most implementations of __array_function__ will start with two checks:  Is the given function something that we know how to overload? Are all arguments of a type that we know how to handle?  If these conditions hold, __array_function__ should return the result from calling its implementation for func(*args, **kwargs). Otherwise, it should return the sentinel value NotImplemented, indicating that the function is not implemented by these types. There are no general requirements on the return value from __array_function__, although most sensible implementations should probably return array(s) with the same type as one of the function’s arguments. It may also be convenient to define a custom decorators (implements below) for registering __array_function__ implementations. HANDLED_FUNCTIONS = {}

class MyArray:
    def __array_function__(self, func, types, args, kwargs):
        if func not in HANDLED_FUNCTIONS:
            return NotImplemented
        # Note: this allows subclasses that don't override
        # __array_function__ to handle MyArray objects
        if not all(issubclass(t, MyArray) for t in types):
            return NotImplemented
        return HANDLED_FUNCTIONS[func](*args, **kwargs)

def implements(numpy_function):
    """Register an __array_function__ implementation for MyArray objects."""
    def decorator(func):
        HANDLED_FUNCTIONS[numpy_function] = func
        return func
    return decorator

@implements(np.concatenate)
def concatenate(arrays, axis=0, out=None):
    ...  # implementation of concatenate for MyArray objects

@implements(np.broadcast_to)
def broadcast_to(array, shape):
    ...  # implementation of broadcast_to for MyArray objects
 Note that it is not required for __array_function__ implementations to include all of the corresponding NumPy function’s optional arguments (e.g., broadcast_to above omits the irrelevant subok argument). Optional arguments are only passed in to __array_function__ if they were explicitly used in the NumPy function call. Just like the case for builtin special methods like __add__, properly written __array_function__ methods should always return NotImplemented when an unknown type is encountered. Otherwise, it will be impossible to correctly override NumPy functions from another object if the operation also includes one of your objects. For the most part, the rules for dispatch with __array_function__ match those for __array_ufunc__. In particular:  NumPy will gather implementations of __array_function__ from all specified inputs and call them in order: subclasses before superclasses, and otherwise left to right. Note that in some edge cases involving subclasses, this differs slightly from the current behavior of Python. Implementations of __array_function__ indicate that they can handle the operation by returning any value other than NotImplemented. If all __array_function__ methods return NotImplemented, NumPy will raise TypeError.  If no __array_function__ methods exists, NumPy will default to calling its own implementation, intended for use on NumPy arrays. This case arises, for example, when all array-like arguments are Python numbers or lists. (NumPy arrays do have a __array_function__ method, given below, but it always returns NotImplemented if any argument other than a NumPy array subclass implements __array_function__.) One deviation from the current behavior of __array_ufunc__ is that NumPy will only call __array_function__ on the first argument of each unique type. This matches Python’s rule for calling reflected methods, and this ensures that checking overloads has acceptable performance even when there are a large number of overloaded arguments.


class.__array_prepare__(array, context=None)

At the beginning of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The output array is passed in and whatever is returned is passed to the ufunc. Subclasses inherit a default implementation of this method which simply returns the output array unmodified. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the ufunc for computation.  Note For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.


class.__array_priority__

The value of this attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. Subclasses inherit a default value of 0.0 for this attribute.  Note For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.


Standard array subclasses  Note Subclassing a numpy.ndarray is possible but if your goal is to create an array with modified behavior, as do dask arrays for distributed computation and cupy arrays for GPU-based computation, subclassing is discouraged. Instead, using numpy’s dispatch mechanism is recommended.  The ndarray can be inherited from (in Python or in C) if desired. Therefore, it can form a foundation for many useful classes. Often whether to sub-class the array object or to simply use the core array component as an internal part of a new class is a difficult decision, and can be simply a matter of choice. NumPy has several tools for simplifying how your new object interacts with other array objects, and so the choice may not be significant in the end. One way to simplify the question is by asking yourself if the object you are interested in can be replaced as a single array or does it really require two or more arrays at its core. Note that asarray always returns the base-class ndarray. If you are confident that your use of the array object can handle any subclass of an ndarray, then asanyarray can be used to allow subclasses to propagate more cleanly through your subroutine. In principal a subclass could redefine any aspect of the array and therefore, under strict guidelines, asanyarray would rarely be useful. However, most subclasses of the array object will not redefine certain aspects of the array object such as the buffer interface, or the attributes of the array. One important example, however, of why your subroutine may not be able to handle an arbitrary subclass of an array is that matrices redefine the “*” operator to be matrix-multiplication, rather than element-by-element multiplication.  Special attributes and methods  See also Subclassing ndarray  NumPy provides several hooks that classes can customize:   class.__array_ufunc__(ufunc, method, *inputs, **kwargs)

 New in version 1.13.  Any class, ndarray subclass or not, can define this method or set it to None in order to override the behavior of NumPy’s ufuncs. This works quite similarly to Python’s __mul__ and other binary operation routines.
ufunc is the ufunc object that was called.
method is a string indicating which Ufunc method was called (one of "__call__", "reduce", "reduceat", "accumulate", "outer", "inner").
inputs is a tuple of the input arguments to the ufunc.
kwargs is a dictionary containing the optional input arguments of the ufunc. If given, any out arguments, both positional and keyword, are passed as a tuple in kwargs. See the discussion in Universal functions (ufunc) for details.  The method should return either the result of the operation, or NotImplemented if the operation requested is not implemented. If one of the input or output arguments has a __array_ufunc__ method, it is executed instead of the ufunc. If more than one of the arguments implements __array_ufunc__, they are tried in the order: subclasses before superclasses, inputs before outputs, otherwise left to right. The first routine returning something other than NotImplemented determines the result. If all of the __array_ufunc__ operations return NotImplemented, a TypeError is raised.  Note We intend to re-implement numpy functions as (generalized) Ufunc, in which case it will become possible for them to be overridden by the __array_ufunc__ method. A prime candidate is matmul, which currently is not a Ufunc, but could be relatively easily be rewritten as a (set of) generalized Ufuncs. The same may happen with functions such as median, amin, and argsort.  Like with some other special methods in python, such as __hash__ and __iter__, it is possible to indicate that your class does not support ufuncs by setting __array_ufunc__ = None. Ufuncs always raise TypeError when called on an object that sets __array_ufunc__ = None. The presence of __array_ufunc__ also influences how ndarray handles binary operations like arr + obj and arr
< obj when arr is an ndarray and obj is an instance of a custom class. There are two possibilities. If obj.__array_ufunc__ is present and not None, then ndarray.__add__ and friends will delegate to the ufunc machinery, meaning that arr + obj becomes np.add(arr, obj), and then add invokes obj.__array_ufunc__. This is useful if you want to define an object that acts like an array. Alternatively, if obj.__array_ufunc__ is set to None, then as a special case, special methods like ndarray.__add__ will notice this and unconditionally raise TypeError. This is useful if you want to create objects that interact with arrays via binary operations, but are not themselves arrays. For example, a units handling system might have an object m representing the “meters” unit, and want to support the syntax arr * m to represent that the array has units of “meters”, but not want to otherwise interact with arrays via ufuncs or otherwise. This can be done by setting __array_ufunc__ = None and defining __mul__ and __rmul__ methods. (Note that this means that writing an __array_ufunc__ that always returns NotImplemented is not quite the same as setting __array_ufunc__ = None: in the former case, arr + obj will raise TypeError, while in the latter case it is possible to define a __radd__ method to prevent this.) The above does not hold for in-place operators, for which ndarray never returns NotImplemented. Hence, arr += obj would always lead to a TypeError. This is because for arrays in-place operations cannot generically be replaced by a simple reverse operation. (For instance, by default, arr += obj would be translated to arr =
arr + obj, i.e., arr would be replaced, contrary to what is expected for in-place array operations.)  Note If you define __array_ufunc__:  If you are not a subclass of ndarray, we recommend your class define special methods like __add__ and __lt__ that delegate to ufuncs just like ndarray does. An easy way to do this is to subclass from NDArrayOperatorsMixin. If you subclass ndarray, we recommend that you put all your override logic in __array_ufunc__ and not also override special methods. This ensures the class hierarchy is determined in only one place rather than separately by the ufunc machinery and by the binary operation rules (which gives preference to special methods of subclasses; the alternative way to enforce a one-place only hierarchy, of setting __array_ufunc__ to None, would seem very unexpected and thus confusing, as then the subclass would not work at all with ufuncs).
ndarray defines its own __array_ufunc__, which, evaluates the ufunc if no arguments have overrides, and returns NotImplemented otherwise. This may be useful for subclasses for which __array_ufunc__ converts any instances of its own class to ndarray: it can then pass these on to its superclass using super().__array_ufunc__(*inputs, **kwargs), and finally return the results after possible back-conversion. The advantage of this practice is that it ensures that it is possible to have a hierarchy of subclasses that extend the behaviour. See Subclassing ndarray for details.    Note If a class defines the __array_ufunc__ method, this disables the __array_wrap__, __array_prepare__, __array_priority__ mechanism described below for ufuncs (which may eventually be deprecated).
   class.__array_function__(func, types, args, kwargs)

 New in version 1.16.   Note  In NumPy 1.17, the protocol is enabled by default, but can be disabled with NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=0. In NumPy 1.16, you need to set the environment variable NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=1 before importing NumPy to use NumPy function overrides. Eventually, expect to __array_function__ to always be enabled.
func is an arbitrary callable exposed by NumPy’s public API, which was called in the form func(*args, **kwargs).
types is a collection collections.abc.Collection of unique argument types from the original NumPy function call that implement __array_function__. The tuple args and dict kwargs are directly passed on from the original call.  As a convenience for __array_function__ implementors, types provides all argument types with an '__array_function__' attribute. This allows implementors to quickly identify cases where they should defer to __array_function__ implementations on other arguments. Implementations should not rely on the iteration order of types. Most implementations of __array_function__ will start with two checks:  Is the given function something that we know how to overload? Are all arguments of a type that we know how to handle?  If these conditions hold, __array_function__ should return the result from calling its implementation for func(*args, **kwargs). Otherwise, it should return the sentinel value NotImplemented, indicating that the function is not implemented by these types. There are no general requirements on the return value from __array_function__, although most sensible implementations should probably return array(s) with the same type as one of the function’s arguments. It may also be convenient to define a custom decorators (implements below) for registering __array_function__ implementations. HANDLED_FUNCTIONS = {}

class MyArray:
    def __array_function__(self, func, types, args, kwargs):
        if func not in HANDLED_FUNCTIONS:
            return NotImplemented
        # Note: this allows subclasses that don't override
        # __array_function__ to handle MyArray objects
        if not all(issubclass(t, MyArray) for t in types):
            return NotImplemented
        return HANDLED_FUNCTIONS[func](*args, **kwargs)

def implements(numpy_function):
    """Register an __array_function__ implementation for MyArray objects."""
    def decorator(func):
        HANDLED_FUNCTIONS[numpy_function] = func
        return func
    return decorator

@implements(np.concatenate)
def concatenate(arrays, axis=0, out=None):
    ...  # implementation of concatenate for MyArray objects

@implements(np.broadcast_to)
def broadcast_to(array, shape):
    ...  # implementation of broadcast_to for MyArray objects
 Note that it is not required for __array_function__ implementations to include all of the corresponding NumPy function’s optional arguments (e.g., broadcast_to above omits the irrelevant subok argument). Optional arguments are only passed in to __array_function__ if they were explicitly used in the NumPy function call. Just like the case for builtin special methods like __add__, properly written __array_function__ methods should always return NotImplemented when an unknown type is encountered. Otherwise, it will be impossible to correctly override NumPy functions from another object if the operation also includes one of your objects. For the most part, the rules for dispatch with __array_function__ match those for __array_ufunc__. In particular:  NumPy will gather implementations of __array_function__ from all specified inputs and call them in order: subclasses before superclasses, and otherwise left to right. Note that in some edge cases involving subclasses, this differs slightly from the current behavior of Python. Implementations of __array_function__ indicate that they can handle the operation by returning any value other than NotImplemented. If all __array_function__ methods return NotImplemented, NumPy will raise TypeError.  If no __array_function__ methods exists, NumPy will default to calling its own implementation, intended for use on NumPy arrays. This case arises, for example, when all array-like arguments are Python numbers or lists. (NumPy arrays do have a __array_function__ method, given below, but it always returns NotImplemented if any argument other than a NumPy array subclass implements __array_function__.) One deviation from the current behavior of __array_ufunc__ is that NumPy will only call __array_function__ on the first argument of each unique type. This matches Python’s rule for calling reflected methods, and this ensures that checking overloads has acceptable performance even when there are a large number of overloaded arguments.
   class.__array_finalize__(obj)

This method is called whenever the system internally allocates a new array from obj, where obj is a subclass (subtype) of the ndarray. It can be used to change attributes of self after construction (so as to ensure a 2-d matrix for example), or to update meta-information from the “parent.” Subclasses inherit a default implementation of this method that does nothing.
   class.__array_prepare__(array, context=None)

At the beginning of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The output array is passed in and whatever is returned is passed to the ufunc. Subclasses inherit a default implementation of this method which simply returns the output array unmodified. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the ufunc for computation.  Note For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.
   class.__array_wrap__(array, context=None)

At the end of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The ufunc-computed array is passed in and whatever is returned is passed to the user. Subclasses inherit a default implementation of this method, which transforms the array into a new instance of the object’s class. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the user.  Note For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.
   class.__array_priority__

The value of this attribute is used to determine what type of object to return in situations where there is more than one possibility for the Python type of the returned object. Subclasses inherit a default value of 0.0 for this attribute.  Note For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.
   class.__array__([dtype])

If a class (ndarray subclass or not) having the __array__ method is used as the output object of an ufunc, results will not be written to the object returned by __array__. This practice will return TypeError.
   Matrix objects  Note It is strongly advised not to use the matrix subclass. As described below, it makes writing functions that deal consistently with matrices and regular arrays very difficult. Currently, they are mainly used for interacting with scipy.sparse. We hope to provide an alternative for this use, however, and eventually remove the matrix subclass.  matrix objects inherit from the ndarray and therefore, they have the same attributes and methods of ndarrays. There are six important differences of matrix objects, however, that may lead to unexpected results when you use matrices but expect them to act like arrays:  Matrix objects can be created using a string notation to allow Matlab-style syntax where spaces separate columns and semicolons (‘;’) separate rows. Matrix objects are always two-dimensional. This has far-reaching implications, in that m.ravel() is still two-dimensional (with a 1 in the first dimension) and item selection returns two-dimensional objects so that sequence behavior is fundamentally different than arrays. Matrix objects over-ride multiplication to be matrix-multiplication. Make sure you understand this for functions that you may want to receive matrices. Especially in light of the fact that asanyarray(m) returns a matrix when m is a matrix.
 Matrix objects over-ride power to be matrix raised to a power. The same warning about using power inside a function that uses asanyarray(…) to get an array object holds for this fact. The default __array_priority__ of matrix objects is 10.0, and therefore mixed operations with ndarrays always produce matrices.
Matrices have special attributes which make calculations easier. These are
matrix.T Returns the transpose of the matrix.
matrix.H Returns the (complex) conjugate transpose of self.
matrix.I Returns the (multiplicative) inverse of invertible self.
matrix.A Return self as an ndarray object.      Warning Matrix objects over-ride multiplication, ‘*’, and power, ‘**’, to be matrix-multiplication and matrix power, respectively. If your subroutine can accept sub-classes and you do not convert to base- class arrays, then you must use the ufuncs multiply and power to be sure that you are performing the correct operation for all inputs.  The matrix class is a Python subclass of the ndarray and can be used as a reference for how to construct your own subclass of the ndarray. Matrices can be created from other matrices, strings, and anything else that can be converted to an ndarray . The name “mat “is an alias for “matrix “in NumPy.
matrix(data[, dtype, copy])
 Note It is no longer recommended to use this class, even for linear
asmatrix(data[, dtype]) Interpret the input as a matrix.
bmat(obj[, ldict, gdict]) Build a matrix object from a string, nested sequence, or array.   Example 1: Matrix creation from a string >>> a = np.mat('1 2 3; 4 5 3')
>>> print((a*a.T).I)
    [[ 0.29239766 -0.13450292]
     [-0.13450292  0.08187135]]
 Example 2: Matrix creation from nested sequence >>> np.mat([[1,5,10],[1.0,3,4j]])
matrix([[  1.+0.j,   5.+0.j,  10.+0.j],
        [  1.+0.j,   3.+0.j,   0.+4.j]])
 Example 3: Matrix creation from an array >>> np.mat(np.random.rand(3,3)).T
matrix([[4.17022005e-01, 3.02332573e-01, 1.86260211e-01],
        [7.20324493e-01, 1.46755891e-01, 3.45560727e-01],
        [1.14374817e-04, 9.23385948e-02, 3.96767474e-01]])
   Memory-mapped file arrays Memory-mapped files are useful for reading and/or modifying small segments of a large file with regular layout, without reading the entire file into memory. A simple subclass of the ndarray uses a memory-mapped file for the data buffer of the array. For small files, the over-head of reading the entire file into memory is typically not significant, however for large files using memory mapping can save considerable resources. Memory-mapped-file arrays have one additional method (besides those they inherit from the ndarray): .flush() which must be called manually by the user to ensure that any changes to the array actually get written to disk.
memmap(filename[, dtype, mode, offset, ...]) Create a memory-map to an array stored in a binary file on disk.
memmap.flush() Write any changes in the array to the file on disk.   Example: >>> a = np.memmap('newfile.dat', dtype=float, mode='w+', shape=1000)
>>> a[10] = 10.0
>>> a[30] = 30.0
>>> del a
>>> b = np.fromfile('newfile.dat', dtype=float)
>>> print(b[10], b[30])
10.0 30.0
>>> a = np.memmap('newfile.dat', dtype=float)
>>> print(a[10], a[30])
10.0 30.0
   Character arrays (numpy.char)  See also Creating character arrays (numpy.char)   Note The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, bytes_ or str_, and use the free functions in the numpy.char module for fast vectorized string operations.  These are enhanced arrays of either str_ type or bytes_ type. These arrays inherit from the ndarray, but specially-define the operations +, *, and % on a (broadcasting) element-by-element basis. These operations are not available on the standard ndarray of character type. In addition, the chararray has all of the standard str (and bytes) methods, executing them on an element-by-element basis. Perhaps the easiest way to create a chararray is to use self.view(chararray) where self is an ndarray of str or unicode data-type. However, a chararray can also be created using the numpy.chararray constructor, or via the numpy.char.array function:
chararray(shape[, itemsize, unicode, ...]) Provides a convenient view on arrays of string and unicode values.
core.defchararray.array(obj[, itemsize, ...]) Create a chararray.   Another difference with the standard ndarray of str data-type is that the chararray inherits the feature introduced by Numarray that white-space at the end of any element in the array will be ignored on item retrieval and comparison operations.   Record arrays (numpy.rec)  See also Creating record arrays (numpy.rec), Data type routines, Data type objects (dtype).  NumPy provides the recarray class which allows accessing the fields of a structured array as attributes, and a corresponding scalar data type object record.
recarray(shape[, dtype, buf, offset, ...]) Construct an ndarray that allows field access using attributes.
record A data-type scalar that allows field access as attribute lookup.     Masked arrays (numpy.ma)  See also Masked arrays    Standard container class For backward compatibility and as a standard “container “class, the UserArray from Numeric has been brought over to NumPy and named numpy.lib.user_array.container The container class is a Python class whose self.array attribute is an ndarray. Multiple inheritance is probably easier with numpy.lib.user_array.container than with the ndarray itself and so it is included by default. It is not documented here beyond mentioning its existence because you are encouraged to use the ndarray class directly if you can.
numpy.lib.user_array.container(data[, ...]) Standard container-class for easy multiple-inheritance.     Array Iterators Iterators are a powerful concept for array processing. Essentially, iterators implement a generalized for-loop. If myiter is an iterator object, then the Python code: for val in myiter:
    ...
    some code involving val
    ...
 calls val = next(myiter) repeatedly until StopIteration is raised by the iterator. There are several ways to iterate over an array that may be useful: default iteration, flat iteration, and \(N\)-dimensional enumeration.  Default iteration The default iterator of an ndarray object is the default Python iterator of a sequence type. Thus, when the array object itself is used as an iterator. The default behavior is equivalent to: for i in range(arr.shape[0]):
    val = arr[i]
 This default iterator selects a sub-array of dimension \(N-1\) from the array. This can be a useful construct for defining recursive algorithms. To loop over the entire array requires \(N\) for-loops. >>> a = np.arange(24).reshape(3,2,4)+10
>>> for val in a:
...     print('item:', val)
item: [[10 11 12 13]
 [14 15 16 17]]
item: [[18 19 20 21]
 [22 23 24 25]]
item: [[26 27 28 29]
 [30 31 32 33]]
   Flat iteration
ndarray.flat A 1-D iterator over the array.   As mentioned previously, the flat attribute of ndarray objects returns an iterator that will cycle over the entire array in C-style contiguous order. >>> for i, val in enumerate(a.flat):
...     if i%5 == 0: print(i, val)
0 10
5 15
10 20
15 25
20 30
 Here, I’ve used the built-in enumerate iterator to return the iterator index as well as the value.   N-dimensional enumeration
ndenumerate(arr) Multidimensional index iterator.   Sometimes it may be useful to get the N-dimensional index while iterating. The ndenumerate iterator can achieve this. >>> for i, val in np.ndenumerate(a):
...     if sum(i)%5 == 0: print(i, val)
(0, 0, 0) 10
(1, 1, 3) 25
(2, 0, 3) 29
(2, 1, 2) 32
   Iterator for broadcasting
broadcast Produce an object that mimics broadcasting.   The general concept of broadcasting is also available from Python using the broadcast iterator. This object takes \(N\) objects as inputs and returns an iterator that returns tuples providing each of the input sequence elements in the broadcasted result. >>> for val in np.broadcast([[1,0],[2,3]],[0,1]):
...     print(val)
(1, 0)
(0, 1)
(2, 0)
(3, 1)


class.__array_wrap__(array, context=None)

At the end of every ufunc, this method is called on the input object with the highest array priority, or the output object if one was specified. The ufunc-computed array is passed in and whatever is returned is passed to the user. Subclasses inherit a default implementation of this method, which transforms the array into a new instance of the object’s class. Subclasses may opt to use this method to transform the output array into an instance of the subclass and update metadata before returning the array to the user.  Note For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.