Pandas 係列是帶有軸標簽的一維ndarray。標簽不必是唯一的,但必須是可哈希的類型。該對象同時支持基於整數和基於標簽的索引,並提供了許多方法來執行涉及索引的操作。
Pandas Series.mask()
函數用於掩蔽目的。此函數替換傳遞條件為的值True
。否則,該值保持不變。
用法: Series.mask(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None)
參數:
cond:如果cond為False,請保留原始值。如果為True,則用其他的相應值替換。
other:cond為True的條目將替換為其他條目的對應值。
inplace:是否對數據執行適當的操作。
axis:對齊軸(如果需要)。
level:對齊級別(如果需要)。
返回:wh:與調用者類型相同
範例1:采用Series.mask()
函數以替換給定係列對象中的“裏約”城市。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio'])
# Create the Index
index_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']
# set the index
sr.index = index_
# Print the series
print(sr)
輸出:
現在我們將使用Series.mask()
函數以替換給定係列對象中的“裏約”城市。
# replace 'Rio' with 'Tokyo'
result = sr.mask(lambda x:x =='Rio', other = 'Tokyo')
# Print the result
print(result)
輸出:
正如我們在輸出中看到的,Series.mask()
函數已成功將給定係列對象中的“裏約”城市替換為“東京”。
範例2:采用Series.mask()
函數屏蔽給定係列對象中大於50的所有值。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series([11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32])
# Print the series
print(sr)
輸出:
現在我們將使用Series.mask()
函數可屏蔽給定係列對象中所有大於50的值。
# mask values greater than 50
result = sr.mask(sr > 50)
# Print the result
print(result)
輸出:
正如我們在輸出中看到的,Series.mask()
函數已成功屏蔽給定係列對象中所有大於50的值。
相關用法
- Python pandas.map()用法及代碼示例
- Python Pandas Timestamp.now用法及代碼示例
- Python Pandas Timestamp.second用法及代碼示例
- Python Pandas DataFrame.abs()用法及代碼示例
- Python Pandas Series.lt()用法及代碼示例
- Python Pandas dataframe.all()用法及代碼示例
- Python Pandas DataFrame.ix[ ]用法及代碼示例
- Python Pandas Series.pop()用法及代碼示例
- Python Pandas TimedeltaIndex.max用法及代碼示例
- Python Pandas Timestamp.dst用法及代碼示例
- Python Pandas Timestamp.tz用法及代碼示例
- Python Pandas Series.mean()用法及代碼示例
- Python Pandas TimedeltaIndex.min用法及代碼示例
- Python Pandas Series.ptp()用法及代碼示例
- Python Pandas dataframe.cov()用法及代碼示例
注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Series.mask()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。