dataframe 使用 np.where(删选
时间: 2024-03-19 18:38:53 浏览: 17
DataFrame 使用 np.where() 函数可以进行条件筛选操作。np.where() 函数的语法如下:
np.where(condition, x, y)
其中,condition 是一个条件表达式,x 和 y 是两个数组或者标量。当条件表达式为 True 时,返回 x;当条件表达式为 False 时,返回 y。
在 DataFrame 中使用 np.where() 函数时,可以根据条件对 DataFrame 的某一列或多列进行筛选操作。例如,假设有一个名为 df 的 DataFrame,我们可以使用 np.where() 函数对其中的某一列进行筛选,示例代码如下:
import pandas as pd
import numpy as np
# 创建 DataFrame
data = {'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10]}
df = pd.DataFrame(data)
# 使用 np.where() 进行条件筛选
df['C'] = np.where(df['A'] > 3, 'High', 'Low')
上述代码中,我们创建了一个包含两列数据的 DataFrame,并使用 np.where() 函数根据条件 df['A'] > 3 对 DataFrame 进行筛选,将满足条件的行标记为 'High',不满足条件的行标记为 'Low'。最终结果如下:
A B C
0 1 6 Low
1 2 7 Low
2 3 8 Low
3 4 9 High
4 5 10 High