**where()**函数可以用来替换pandas DataFrame中的某些值。
这个函数使用以下基本语法。
df.where(cond, other=nan)
对于 pandas DataFrame 中cond为 True 的每一个值,原值被保留。
对于cond为False的每个值,原始值将被另一个参数指定的值所取代。
下面的例子展示了如何在实践中使用这种语法,比如下面这个pandas DataFrame。
import pandas as pd
#define DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
df
points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12
例1:替换整个数据框架中的值
下面的代码展示了如何使用**where()**函数将整个pandas DataFrame中不符合某个条件的所有值替换为NaN值。
#keep values that are greater than 7, but replace all others with NaN
df.where(df>7)
points assists rebounds
0 25 NaN 11.0
1 12 NaN 8.0
2 15 NaN 10.0
3 14 9.0 NaN
4 19 12.0 NaN
5 23 9.0 NaN
6 25 9.0 9.0
7 29 NaN 12.0
我们也可以使用另一个参数来替换NaN以外的值。
#keep values that are greater than 7, but replace all others with 'low'
df.where(df>7, other='low')
points assists rebounds
0 25 low 11
1 12 low 8
2 15 low 10
3 14 9 low
4 19 12 low
5 23 9 low
6 25 9 9
7 29 low 12
例2:替换DataFrame中特定列的值
下面的代码显示了如何使用**where()**函数来替换DataFrame某一列中不符合特定条件的所有数值。
#keep values greater than 15 in 'points' column, but replace others with 'low'
df['points'] = df['points'].where(df['points']>15, other='low')
#view DataFrame
df
points assists rebounds
0 25 5 11
1 low 7 8
2 low 7 10
3 low 9 6
4 19 12 6
5 23 9 5
6 25 9 9
7 29 4 12
你可以在这里找到pandas**where()**函数的完整在线文档。
其他资源
下面的教程介绍了如何使用pandas中的其他常用函数。
如何在Pandas中使用describe()函数
如何在Pandas中使用idxmax()函数
如何在Pandas中对选定的列应用一个函数
The postHow to Use where() Function in Pandas (With Examples) appeared first onStatology.