Python numpy.char.encode() Method (With Examples)

By IncludeHelp Last updated : December 1, 2023

Python numpy.char.encode() Method

The encode() method is a built-in method of the char class in the numpy module, it is used to encode the given array like string or Unicode element-wise. This operation is performed by calling the str.encode() method element-wise.

Module

The following module is required to use the encode() method:

import numpy as np

Syntax

The following is the syntax of the encode() method:

char.encode(arr, encoding = None, errors = None)

Parameter(s)

The following are the parameter(s):

  • arr: An array of strings or Unicode to be encoded with a specified encoding type.
  • encoding: The name of the encoding. It's an optional parameter of str type with the default value as None.
  • errors: Specifies the method to handle errors. It's an optional parameter of str type with the default value as None.

Return Value

The return type of the encode() method is <class 'numpy.ndarray'>, it returns an element-wise encoded string. Return type may depend on the specified encoding.

Example 1: Applying char.encode() method on a single-element array

# Importing numpy module
import numpy as np

# Creating an array
arr = ["Hello World!"]
# Encoding Type
encoding = "cp037"

# Using char.encode() method
result = np.char.encode(arr, encoding)

# Printing the result
print("\nThe result is:", result)
print("\nThe type of the result is:", type(result))

Output

The output of the above example is:

The result is: [b'\xc8\x85\x93\x93\x96@\xe6\x96\x99\x93\x84Z']

The type of the result is: <class 'numpy.ndarray'>

Example 2: Applying char.encode() method on an array of strings

# Importing numpy module
import numpy as np

# Creating an array of strings
arr = ["Hello" "Hi" "How're you?"]
# Encoding Type
encoding = "cp037"

# Using char.encode() method
result = np.char.encode(arr, encoding)

# Printing the result
print("\nThe result is:", result)
print("\nThe type of the result is:", type(result))

Output

The output of the above example is:

The result is: [b'\xc8\x85\x93\x93\x96\xc8\x89\xc8\x96\xa6}\x99\x85@\xa8\x96\xa4o']

The type of the result is: <class 'numpy.ndarray'>

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.