This tutorial will discuss about unique ways to check if numpy array contains only empty strings.
Table Of Contents
Method 1: using numpy.char.str_len()
The numpy
module in Python provides a function numpy.char.str_len()
. It accepts a string array as an argument, and returns an array of integers. In the returned array, a value at the ith
index represents the size of string at the ith
index in passed string array.
So, to check if a Numpy Array contains only empty strings, we can pass the NumPy array to method numpy.char.str_len()
, and compare the returned array with zero. It will give a Boolean Array. In this array, each True value represents that the corresponding value in the original NumPy array is an empty string.
Then we can use the numpy.all()
method to check if boolean array has only True values or not. If it returns True, then it means original numpy array has empty strings only.
Frequently Asked:
Let’s see the complete example,
import numpy as np # Create a NumPy Array arr = np.array(['', '', '']) # check if numpy array has empty strings if np.all(np.char.str_len(arr) == 0): print("The NumPy Array contains only empty strings") else: print("The NumPy Array does not contain only empty strings")
Output
The NumPy Array contains only empty strings
Method 2: using all() method
Iterate over all strings of NumPy Array, and for each string check if its size is 0 or not. Do, all this in a generator expression, and it will give a boolean list. In this list, each True value represents that the corresponding value in the original numpy array is an empty string.
Then we can use the all()
method to check if boolean list has only True values or not. If it returns True, then it means original numpy array has empty strings only.
Latest Python - Video Tutorial
Let’s see the complete example,
import numpy as np # Create a NumPy Array arr = np.array(['', '', '']) # check if numpy array has empty strings if all(len(x) == 0 for x in arr): print("The NumPy Array contains only empty strings") else: print("The NumPy Array does not contain only empty strings")
Output
The NumPy Array contains only empty strings
Summary
We learned about two different ways to check if a NumPy array has only empty strings in Python. Thanks.
Latest Video Tutorials