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