doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
numpy.char.chararray.reshape method char.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.reference.generated.numpy.char.chararray.reshape |
numpy.char.chararray.resize method char.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.reference.generated.numpy.char.chararray.resize |
numpy.char.chararray.rfind method char.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.reference.generated.numpy.char.chararray.rfind |
numpy.char.chararray.rindex method char.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.reference.generated.numpy.char.chararray.rindex |
numpy.char.chararray.rjust method char.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.reference.generated.numpy.char.chararray.rjust |
numpy.char.chararray.rsplit method char.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.reference.generated.numpy.char.chararray.rsplit |
numpy.char.chararray.rstrip method char.chararray.rstrip(chars=None)[source]
For each element in self, return a copy with the trailing characters removed. See also char.rstrip | numpy.reference.generated.numpy.char.chararray.rstrip |
numpy.char.chararray.searchsorted method char.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.reference.generated.numpy.char.chararray.searchsorted |
numpy.char.chararray.setfield method char.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.reference.generated.numpy.char.chararray.setfield |
numpy.char.chararray.setflags method char.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.reference.generated.numpy.char.chararray.setflags |
numpy.char.chararray.shape attribute char.chararray.shape
Tuple of array dimensions. The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required. See also numpy.reshape
similar function ndarray.reshape
similar method Examples >>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
>>> y = np.zeros((2, 3, 4))
>>> y.shape
(2, 3, 4)
>>> y.shape = (3, 8)
>>> y
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])
>>> y.shape = (3, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: total size of new array must be unchanged
>>> np.zeros((4,2))[::2].shape = (-1,)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Incompatible shape for in-place modification. Use
`.reshape()` to make a copy with the desired shape. | numpy.reference.generated.numpy.char.chararray.shape |
numpy.char.chararray.size attribute char.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.reference.generated.numpy.char.chararray.size |
numpy.char.chararray.sort method char.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.reference.generated.numpy.char.chararray.sort |
numpy.char.chararray.split method char.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.reference.generated.numpy.char.chararray.split |
numpy.char.chararray.splitlines method char.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.reference.generated.numpy.char.chararray.splitlines |
numpy.char.chararray.squeeze method char.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.reference.generated.numpy.char.chararray.squeeze |
numpy.char.chararray.startswith method char.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.reference.generated.numpy.char.chararray.startswith |
numpy.char.chararray.strides attribute char.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.reference.generated.numpy.char.chararray.strides |
numpy.char.chararray.strip method char.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.reference.generated.numpy.char.chararray.strip |
numpy.char.chararray.swapaxes method char.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.reference.generated.numpy.char.chararray.swapaxes |
numpy.char.chararray.swapcase method char.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.reference.generated.numpy.char.chararray.swapcase |
numpy.char.chararray.T attribute char.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.reference.generated.numpy.char.chararray.t |
numpy.char.chararray.take method char.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.reference.generated.numpy.char.chararray.take |
numpy.char.chararray.title method char.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.reference.generated.numpy.char.chararray.title |
numpy.char.chararray.tobytes method char.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.reference.generated.numpy.char.chararray.tobytes |
numpy.char.chararray.tofile method char.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.reference.generated.numpy.char.chararray.tofile |
numpy.char.chararray.tolist method char.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.reference.generated.numpy.char.chararray.tolist |
numpy.char.chararray.tostring method char.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.reference.generated.numpy.char.chararray.tostring |
numpy.char.chararray.translate method char.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.reference.generated.numpy.char.chararray.translate |
numpy.char.chararray.transpose method char.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.reference.generated.numpy.char.chararray.transpose |
numpy.char.chararray.upper method char.chararray.upper()[source]
Return an array with the elements of self converted to uppercase. See also char.upper | numpy.reference.generated.numpy.char.chararray.upper |
numpy.char.chararray.view method char.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.reference.generated.numpy.char.chararray.view |
numpy.char.chararray.zfill method char.chararray.zfill(width)[source]
Return the numeric string left-filled with zeros in a string of length width. See also char.zfill | numpy.reference.generated.numpy.char.chararray.zfill |
numpy.char.compare_chararrays char.compare_chararrays(a1, a2, cmp, rstrip)
Performs element-wise comparison of two string arrays using the comparison operator specified by cmp_op. Parameters
a1, a2array_like
Arrays to be compared.
cmp{“<”, “<=”, “==”, “>=”, “>”, “!=”}
Type of comparison.
rstripBoolean
If True, the spaces at the end of Strings are removed before the comparison. Returns
outndarray
The output array of type Boolean with the same shape as a and b. Raises
ValueError
If cmp_op is not valid. TypeError
If at least one of a or b is a non-string array Examples >>> a = np.array(["a", "b", "cde"])
>>> b = np.array(["a", "a", "dec"])
>>> np.compare_chararrays(a, b, ">", True)
array([False, True, False]) | numpy.reference.generated.numpy.char.compare_chararrays |
numpy.char.count char.count(a, sub, start=0, end=None)[source]
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. Calls str.count element-wise. Parameters
aarray_like of str or unicode
substr or unicode
The substring to search for.
start, endint, optional
Optional arguments start and end are interpreted as slice notation to specify the range in which to count. Returns
outndarray
Output array of ints. See also str.count
Examples >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.char.count(c, 'A')
array([3, 1, 1])
>>> np.char.count(c, 'aA')
array([3, 1, 0])
>>> np.char.count(c, 'A', start=1, end=4)
array([2, 1, 1])
>>> np.char.count(c, 'A', start=1, end=3)
array([1, 0, 0]) | numpy.reference.generated.numpy.char.count |
numpy.char.decode char.decode(a, encoding=None, errors=None)[source]
Calls str.decode element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module. Parameters
aarray_like of str or unicode
encodingstr, optional
The name of an encoding
errorsstr, optional
Specifies how to handle encoding errors Returns
outndarray
See also str.decode
Notes The type of the result will depend on the encoding specified. Examples >>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.char.encode(c, encoding='cp037')
array(['\x81\xc1\x81\xc1\x81\xc1', '@@\x81\xc1@@',
'\x81\x82\xc2\xc1\xc2\x82\x81'],
dtype='|S7') | numpy.reference.generated.numpy.char.decode |
numpy.char.encode char.encode(a, encoding=None, errors=None)[source]
Calls str.encode element-wise. The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module. Parameters
aarray_like of str or unicode
encodingstr, optional
The name of an encoding
errorsstr, optional
Specifies how to handle encoding errors Returns
outndarray
See also str.encode
Notes The type of the result will depend on the encoding specified. | numpy.reference.generated.numpy.char.encode |
numpy.char.endswith char.endswith(a, suffix, start=0, end=None)[source]
Returns a boolean array which is True where the string element in a ends with suffix, otherwise False. Calls str.endswith element-wise. Parameters
aarray_like of str or unicode
suffixstr
start, endint, optional
With optional start, test beginning at that position. With optional end, stop comparing at that position. Returns
outndarray
Outputs an array of bools. See also str.endswith
Examples >>> s = np.array(['foo', 'bar'])
>>> s[0] = 'foo'
>>> s[1] = 'bar'
>>> s
array(['foo', 'bar'], dtype='<U3')
>>> np.char.endswith(s, 'ar')
array([False, True])
>>> np.char.endswith(s, 'a', start=1, end=2)
array([False, True]) | numpy.reference.generated.numpy.char.endswith |
numpy.char.equal char.equal(x1, x2)[source]
Return (x1 == x2) element-wise. Unlike numpy.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
not_equal, greater_equal, less_equal, greater, less | numpy.reference.generated.numpy.char.equal |
numpy.char.expandtabs char.expandtabs(a, tabsize=8)[source]
Return a copy of each string element where all tab characters are replaced by one or more spaces. Calls str.expandtabs element-wise. Return a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given tabsize. The column number is reset to zero after each newline occurring in the string. This doesn’t understand other non-printing characters or escape sequences. Parameters
aarray_like of str or unicode
Input array
tabsizeint, optional
Replace tabs with tabsize number of spaces. If not given defaults to 8 spaces. Returns
outndarray
Output array of str or unicode, depending on input type See also str.expandtabs | numpy.reference.generated.numpy.char.expandtabs |
numpy.char.find char.find(a, sub, start=0, end=None)[source]
For each element, return the lowest index in the string where substring sub is found. Calls str.find element-wise. For each element, return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. 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 or int
Output array of ints. Returns -1 if sub is not found. See also str.find | numpy.reference.generated.numpy.char.find |
numpy.char.greater char.greater(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, less | numpy.reference.generated.numpy.char.greater |
numpy.char.greater_equal char.greater_equal(x1, x2)[source]
Return (x1 >= x2) element-wise. Unlike numpy.greater_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, less_equal, greater, less | numpy.reference.generated.numpy.char.greater_equal |
numpy.char.index char.index(a, sub, start=0, end=None)[source]
Like find, but raises ValueError when the substring is not found. Calls str.index element-wise. Parameters
aarray_like of str or unicode
substr or unicode
start, endint, optional
Returns
outndarray
Output array of ints. Returns -1 if sub is not found. See also
find, str.find | numpy.reference.generated.numpy.char.index |
numpy.char.isalnum char.isalnum(a)[source]
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. Calls str.isalnum element-wise. For 8-bit strings, this method is locale-dependent. Parameters
aarray_like of str or unicode
Returns
outndarray
Output array of str or unicode, depending on input type See also str.isalnum | numpy.reference.generated.numpy.char.isalnum |
numpy.char.isalpha char.isalpha(a)[source]
Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. Calls str.isalpha 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.isalpha | numpy.reference.generated.numpy.char.isalpha |
numpy.char.isdecimal char.isdecimal(a)[source]
For each element, return True if there are only decimal characters in the element. Calls unicode.isdecimal element-wise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Parameters
aarray_like, unicode
Input array. Returns
outndarray, bool
Array of booleans identical in shape to a. See also unicode.isdecimal | numpy.reference.generated.numpy.char.isdecimal |
numpy.char.isdigit char.isdigit(a)[source]
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. Calls str.isdigit 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.isdigit | numpy.reference.generated.numpy.char.isdigit |
numpy.char.islower char.islower(a)[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. Calls str.islower 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.islower | numpy.reference.generated.numpy.char.islower |
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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.less |
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.reference.generated.numpy.char.less_equal |
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.reference.generated.numpy.char.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.reference.generated.numpy.char.lower |
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.reference.generated.numpy.char.lstrip |
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.reference.generated.numpy.char.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.reference.generated.numpy.char.multiply |
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.reference.generated.numpy.char.not_equal |
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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.rsplit |
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.reference.generated.numpy.char.rstrip |
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.reference.generated.numpy.char.split |
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.reference.generated.numpy.char.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.reference.generated.numpy.char.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.reference.generated.numpy.char.str_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.reference.generated.numpy.char.strip |
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.reference.generated.numpy.char.swapcase |
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.reference.generated.numpy.char.title |
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.reference.generated.numpy.char.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.reference.generated.numpy.char.upper |
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.reference.generated.numpy.char.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.reference.generated.numpy.chararray.argsort |
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.reference.generated.numpy.chararray.astype |
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.reference.generated.numpy.chararray.base |
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.reference.generated.numpy.chararray.copy |
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.reference.generated.numpy.chararray.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.reference.generated.numpy.chararray.ctypes |
numpy.chararray.data attribute chararray.data
Python buffer object pointing to the start of the array’s data. | numpy.reference.generated.numpy.chararray.data |
numpy.chararray.decode method chararray.decode(encoding=None, errors=None)[source]
Calls str.decode element-wise. See also char.decode | numpy.reference.generated.numpy.chararray.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.reference.generated.numpy.chararray.dump |
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.reference.generated.numpy.chararray.dumps |
numpy.chararray.encode method chararray.encode(encoding=None, errors=None)[source]
Calls str.encode element-wise. See also char.encode | numpy.reference.generated.numpy.chararray.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.reference.generated.numpy.chararray.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.reference.generated.numpy.chararray.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.reference.generated.numpy.chararray.fill |
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.reference.generated.numpy.chararray.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.reference.generated.numpy.chararray.flags |
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.reference.generated.numpy.chararray.flat |
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.reference.generated.numpy.chararray.flatten |
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.reference.generated.numpy.chararray.getfield |
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.reference.generated.numpy.chararray.index |
Subsets and Splits