
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Decode String Array Values in NumPy
To decode string array values that is already encoded, use the numpy.char.decode() method in Python Numpy. The "encoding" parameter sets the name of the encode used while encoding. The set of available codecs comes from the Python standard library, and may be extended at runtime. The type of the result will depend on the encoding specified.
The numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_ or numpy.bytes_.
Steps
At first, import the required library −
import numpy as np
Create a One-Dimensional array of string −
arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad'])
Displaying our array −
print("Array...
",arr)
Get the datatype −
print("
Array datatype...
",arr.dtype)
Get the dimensions of the Array −
print("
Array Dimensions...
",arr.ndim)
Get the shape of the Array −
print("
Our Array Shape...
",arr.shape)
Get the number of elements of the Array −
print("
Elements in the Array...
",arr.size)
Encode string array values. The arr is the input array to be encoded −
e = np.char.encode(arr, encoding='cp037') print("
Encoded...
",e)
To decode string array values that is already encoded, use the numpy.char.decode() method in Python Numpy. The "encoding" parameter sets the name of the encode used while encoding −
print("
Result (decode)...
",np.char.decode(e, encoding='cp037'))
Example
import numpy as np # Create a One-Dimensional array of string arr = np.array(['Bella', 'Tom', 'John', 'Kate', 'Amy', 'Brad']) # Displaying our array print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # Encode string array values # The arr is the input array to be encoded e = np.char.encode(arr, encoding='cp037') print("
Encoded...
",e) # To decode string array values that is already encoded, use the numpy.char.decode() method in Python Numpy # The "encoding" parameter sets the name of the encode used while encoding print("
Result (decode)...
",np.char.decode(e, encoding='cp037'))
Output
Array... ['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad'] Array datatype... <U5 Array Dimensions... 1 Our Array Shape... (6,) Elements in the Array... 6 Encoded... [b'\xc2\x85\x93\x93\x81' b'\xe3\x96\x94' b'\xd1\x96\x88\x95' b'\xd2\x81\xa3\x85' b'\xc1\x94\xa8' b'\xc2\x99\x81\x84'] Result (decode)... ['Bella' 'Tom' 'John' 'Kate' 'Amy' 'Brad']