Python | Pandas Series.str.isspace () Method



Pandas isspace() — this is a string method, it checks for All-Space characters in a series and returns True for those items only. Since this is a string method, the prefix str must be specified before calling this method.

Syntax: Series.str .isspace ()
Return type: Boolean Series

Example # 1:
In this example, a series is created from python list using Pandas .Series () method. This series is by default a sequence of lines with some elements in the All-space format.  str.isspace () method str.isspace () and the result is stored in the variable result1 and displayed.

# pandas module import

import pandas as pd 

 
# import numpy module

import numpy as np 

 
# create series 1

series1 = pd.Series ([ `a` , ` b` , ` ` , `c` , `d` , ` ` , np.nan]) 

  
# check all space elements in series1

result1 = series1. str . isspace ()

  
# display

print ( `Series 1 results:` , result1)

Output:
As shown in the output, True was returned wherever the matching element was All-space, otherwise, False was returned. Also, as you can see, the last item in the series — this is np.nan and hence the output was also NaN.

 Series 1 results: 0 False 1 False 2 True 3 False 4 False 5 True 6 NaN dtype: object  

Example # 2: Handling errors and transforming rows with .astype()

Since this is a string method, only applicable to string rows. Applying it to a number series returns the error value. Therefore, for this method to work, the data type of the row must be converted to str. The series data type is converted using Pandas astype () .

# pandas module import

import pandas as pd 

 
# create series 2

series2 = pd.Series ([ 1 , 2 , 3 , 10 , 2 ]) 

 
# try except for series2
# since series 2 is a numeric series

try :

  result2 = series2. str . isspace ()

  print ( ` Series 2 results: ` , result2)

 

except Exception as e:

 

# printing error in

print ( `Error occured - {}` . format (e))

 

# new result when first converted to string

# using. astype ()

result2 = series2.astype ( str ). str . isspace ()

 

# print results

print ( `Series 2 results:` , result2)

Output:
As you can see, the challenge this method returns a value error for numeric series. The data must be converted to str using the .astype () method. Since all values ​​were numeric and not whitespace, False was returned for all values.

 Error occured - Can only use .str accessor with string values, which use np.object_ dtype in pandas Series 2 results: 0 False 1 False 2 False 3 False 4 False dtype: bool