Python | Метод Pandas Series.str.isspace ()

Опубликовано: 29 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

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.

# importing pandas module  
import pandas as pd  
    
# importing numpy module 
import numpy as np 
    
# creating series 1 
series1 = pd.Series(["a", "b", "  ", " c ", "d", "  ", np.nan]) 
  
# checking for 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 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().

# importing pandas module  
import pandas as pd  
    
# creating 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 by first converting to string series
    # using .astype()
    result2 = series2.astype(str).str.isspace()
      
    # printing results
    print(" Series 2 results: ", result2)

Выход:
Как видно, вызов этого метода для числового ряда возвращает ошибку значения. Данные необходимо преобразовать в str с помощью метода .astype (). Поскольку все значения были числовыми, а не пробелами, для всех значений возвращалось значение False.

 Произошла ошибка - можно использовать аксессор .str только со строковыми значениями, 
которые используют np.object_ dtype в пандах

Результаты 2-й серии: 

 0 ложь
1 ложь
2 ложь
3 ложь
4 ложно
dtype: bool

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.