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

By IncludeHelp Last updated : December 1, 2023

Python numpy.char.decode() Method

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

Module

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

import numpy as np

Syntax

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

char.decode(arr, encoding = None, error = None)

Parameter(s)

The following are the parameter(s):

  • arr: An array of strings or Unicode. (Often contains encoded byte array)
  • 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 decode() method is <class 'numpy.ndarray'>, it returns an element-wise decoded string. Return type may depend on the specified encoding.

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

# Importing numpy module
import numpy as np

# Creating encoded byte array
arr = np.array([b"\xc8\x85\x93\x93\x96@\xe6\x96\x99\x93\x84Z"])
# Encoding Type
encoding = "cp037"

# Using char.decode() method
result = np.char.decode(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: ['Hello World!']

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

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

# Importing numpy module
import numpy as np

# Creating encoded byte array
arr = np.array(
    [b"\xc8\x85\x93\x93\x96", b"\xc8\x89", b"\xc8\x96\xa6}\x99\x85@\xa8\x96\xa4o"]
)

# Encoding Type
encoding = "cp037"

# Using char.decode() method
result = np.char.decode(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: ['Hello' 'Hi' "How're you?"]

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.