Python | Панды Series.mask ()
Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.
Pandas Series.mask() function is used for masking purpose. This function replace values where the passed condition is True. Otherwise the value remains same.
Syntax: Series.mask(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None)
Parameter :
cond : Where cond is False, keep the original value. Where True, replace with corresponding value from other.
other : Entries where cond is True are replaced with corresponding value from other.
inplace : Whether to perform the operation in place on the data.
axis : Alignment axis if needed.
level : Alignment level if needed.Returns : wh : same type as caller
Example #1: Use Series.mask() function to replace the ‘Rio’ city in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio"]) # Create the Indexindex_ = ["City 1", "City 2", "City 3", "City 4", "City 5"] # set the indexsr.index = index_ # Print the seriesprint(sr) |
Выход :

Now we will use Series.mask() function to replace the ‘Rio’ city in the given series object.
# replace "Rio" with "Tokyo"result = sr.mask(lambda x : x =="Rio", other = "Tokyo") # Print the resultprint(result) |
Выход :

As we can see in the output, the Series.mask() function has successfully replaced the ‘Rio’ city with ‘Tokyo’ in the given series object.
Example #2: Use Series.mask() function to mask all the values in the given series object which are greater than 50.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]) # Print the seriesprint(sr) |
Выход :
Now we will use Series.mask() function to mask all the values greater than 50 in the given series object.
# mask values greater than 50result = sr.mask(sr > 50) # Print the resultprint(result) |
Output :
As we can see in the output, the Series.mask() function has successfully masked all the values greater than 50 in the given series object.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.