Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

NumPy: chararray() function

numpy.core.defchararray.chararray() function

The numpy.core.defchararray.chararray() function provides a convenient view on arrays of string and unicode values.

Versus a regular NumPy array of type str or unicode, this class adds the following functionality:

  • values automatically have whitespace removed from the end when indexed
  • comparison operators automatically remove whitespace from the end when comparing values
  • vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*", "%")

Syntax:

class numpy.core.defchararray.chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order=None)

Parameter:

Name Description Required /
Optional
shape: tuple Shape of the array. Required
itemsize: int Length of each array element, in number of characters. Default is 1. Optional
unicode: bool Are the array elements of type unicode (True) or string (False). Default is False. Optional
buffer: bool Memory address of the start of the array data. Default is None, in which case a new array is created. Optional
offset: int Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0. Optional
strides: array_like of ints Strides for the array (see ndarray.strides for full description). Default is None. Optional
order: {‘C’, ‘F’} The order in which the array data is stored in memory: 'C' -> “row major” order (the default), 'F' -> “column major” (Fortran) order. Optional

Return value:

.

Example-1: numpy.chararray() function

>>> import numpy as np
>>> charary = np.chararray((4, 5))
>>> charary[:] = 'x'
>>> charary
chararray([[b'x', b'x', b'x', b'x', b'x'],
       [b'x', b'x', b'x', b'x', b'x'],
       [b'x', b'x', b'x', b'x', b'x'],
       [b'x', b'x', b'x', b'x', b'x']], 
      dtype='|S1')

Example-2: numpy.chararray() function

>>> import numpy as np
>>> charary = np.chararray(charary.shape, itemsize=7)
>>> charary[:] = 'abc' 
>>> charary
chararray([[b'abc', b'abc', b'abc', b'abc', b'abc'],
       [b'abc', b'abc', b'abc', b'abc', b'abc'],
       [b'abc', b'abc', b'abc', b'abc', b'abc'],
       [b'abc', b'abc', b'abc', b'abc', b'abc']], 
      dtype='|S7')

Python - NumPy Code Editor:

Previous: startswith()
Next: NumPy Data type Home