Python | Pandas Series.str.isspace() method
Last Updated :
06 Jun, 2022
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analysing data much easier. Pandas isspace() is a string method, it checks for All-Space characters in a series and returns True for those elements only. Since it is a string method, str has to be prefixed every time before calling this method.
Syntax: Series.str.isspace() Return type: Boolean Series
Example #1: In this example, a series is made from a python list using Pandas .Series() method. The series is by default a string series with some elements as All-space. str.isspace() method is called on the series and the result is stored in variable result1 and displayed.
Python3
import pandas as pd
import numpy as np
series1 = pd.Series([ 'a' , 'b' , ' ' , ' c ' , 'd' , ' ' , np.nan])
result1 = series1. str .isspace()
print ( 'Series 1 results:\n\n' , result1)
|
Output: As shown in the output, True was returned wherever corresponding element was All-space else False was returned. Also as it can be seen, the last element in the series 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 error and converting series using .astype() Since this is a string method applicable only on string series. Applying it on numeric series returns value error. Hence data type of the series has to be converted to str for this method to work. Data type of series is converted using Pandas astype().
Python3
import pandas as pd
series2 = pd.Series([ 1 , 2 , 3 , 10 , 2 ])
try :
result2 = series2. str .isspace()
print ( 'Series 2 results: \n\n' , result2)
except Exception as e:
print ( '\nError occurred - {}' . format (e))
result2 = series2.astype( str ). str .isspace()
print ( '\nSeries 2 results: \n\n' , result2)
|
Output: As it can be seen, calling this method on numeric series returns a value error. The data needs to be converted to str using .astype() method. Since all values were numeric and not all-space, False was returned for all values.
Error occurred - 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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...