你可以使用NumPywhere()函数,使用if-else逻辑快速更新NumPy数组中的值。
例如,下面的代码显示了如何更新一个NumPy数组中满足某个条件的数值。
import numpy as np
#create NumPy array of values
x = np.array([1, 3, 3, 6, 7, 9])
#update valuesin array based on condition
x = np.where((x < 5) | (x > 8), x/2, x)
#view updated array
x
array([0.5, 1.5, 1.5, 6. , 7. , 4.5])
如果数组中的某个值小于5或大于8,我们就把这个值除以2。
否则,我们保持该值不变。
我们可以通过使用pandaswhere()函数在pandas DataFrame中执行类似的操作,但语法略有不同。
下面是使用NumPy where()函数的基本语法:
x = np.where(condition, value_if_true, value_if_false)
这里是使用pandas where()函数的基本语法:
df['col'] = (value_if_false).where(condition, value_if_true)
下面的例子展示了如何在实践中使用pandas where()函数。
例子Pandas中np.where()的等价物
假设我们有如下的pandas DataFrame。
import pandas as pd
#create DataFrame
df = pd.DataFrame({'A': [18, 22, 19, 14, 14, 11, 20, 28],
'B': [5, 7, 7, 9, 12, 9, 9, 4]})
#view DataFrame
print(df)
A B
0 18 5
1 22 7
2 19 7
3 14 9
4 14 12
5 11 9
6 20 9
7 28 4
我们可以使用下面的pandaswhere()函数,根据一个特定的条件来更新A列的值。
#update values in column A based on condition
df['A'] = (df['A'] / 2).where(df['A'] < 20, df['A'] * 2)
#view updated DataFrame
print(df)
A B
0 9.0 5
1 44.0 7
2 9.5 7
3 7.0 9
4 7.0 12
5 5.5 9
6 40.0 9
7 56.0 4
如果A列中的一个给定值小于20,我们将该值乘以2。
否则,我们将该值除以2。
其他资源
下面的教程解释了如何在pandas中执行其他常见操作:
Pandas:如何用条件计算列中的值
Pandas:如何根据条件在数据框中删除行
Pandas:如何根据条件替换列中的值