LAST UPDATED: DECEMBER 9, 2020
NumPy decode() function
In this tutorial, we will cover decode()
function of the char module of the Numpy library.
The decode()
function in the NumPy is used to decode the input string based on the codec specified. The set of available codecs are taken from the Python standard library.
This function calls the str.decode
in an element-wise manner.
Syntax of decode()
:
The syntax required to use this function is as follows:
numpy.char.decode(a, encoding=None, errors=None)
The above syntax indicates that decode()
is a function of the char module and takes two parameters in the NumPy library.
Parameters:
Let us discuss the parameters of this function:
-
a
This parameter indicates an array of string
-
encoding
This is an optional parameter that denotes the name of the encoding.
-
errors
This parameter is used to specify how to handle errors.
Returned Values:
The decode()
function will always return a decoded string.
Basic Example of decode()
:
The code snippet is as follows where we will use decode()
function:
import numpy as np
x = np.array(['aAaAaArt', ' aABbV ', 'abBABba'])
print("Input is :", x)
e = np.char.encode(x, encoding='cp500')
print("\nAfter encoding: ", e)
d = np.char.decode(e, encoding='cp500')
print("\nAfter decoding: ", d)
Input is : ['aAaAaArt' ' aABbV ' 'abBABba']
After encoding: [b'\x81\xc1\x81\xc1\x81\xc1\x99\xa3' b'@@\x81\xc1\xc2\x82\xe5@'
b'\x81\x82\xc2\xc1\xc2\x82\x81']
After decoding: ['aAaAaArt' ' aABbV ' 'abBABba']
Summary
In this tutorial we learned about the decode()
function of the Numpy library. We have covered how it is used with its syntax and values returned by this function.