Python Pandas - 用特定值遮蔽和替換 NaN
要遮蔽 NaN 並用特定值替換它們,使用 index.putmask() 方法。在其中,設定 index.isna() 方法。
首先,匯入所需的庫 -
import pandas as pd import numpy as np
使用一些 NaN 建立 Pandas 索引 −
index = pd.Index([5, 65, 10, np.nan, 75, np.nan])
顯示 Pandas 索引 −
print("Pandas Index...\n",index)遮蔽 NaN 索引值並用特定值替換它們 −
print("\nMask...\n",index.putmask(index.isna(), 111))
示例
以下為程式碼 −
import pandas as pd
import numpy as np
# Creating Pandas index with some NaNs
index = pd.Index([5, 65, 10, np.nan, 75, np.nan])
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# mask and replace NaN index values with a specific value
print("\nMask...\n",index.putmask(index.isna(), 111))輸出
這將生成以下輸出 −
Pandas Index... Float64Index([5.0, 65.0, 10.0, nan, 75.0, nan], dtype='float64') Number of elements in the index... 6 Mask... Float64Index([5.0, 65.0, 10.0, 111.0, 75.0, 111.0], dtype='float64')
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP