在DataFrame中使用np.select

在DataFrame中使用np.select可以根据不同条件对DataFrame的列进行赋值操作。

example:创建了一个包含学生姓名和成绩的DataFrame,接着定义了一系列条件以及对应的等级标签,最后借助np.select函数依据这些条件为每个学生添加了等级标签。

import pandas as pd
import numpy as np

# 创建示例 DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Score': [85, 60, 92, 45]}
df = pd.DataFrame(data)

# 定义条件和对应的选择
conditions = [
    df['Score'] >= 90,
    (df['Score'] >= 80) & (df['Score'] < 90),
    (df['Score'] >= 60) & (df['Score'] < 80),
    df['Score'] < 60
]
choices = ['A', 'B', 'C', 'D']

# 使用 np.select 创建新列
df['Grade'] = np.select(conditions, choices, default='Unknown')

print(df)

posted @ 2025-04-30 11:25  华小电  阅读(85)  评论(0)    收藏  举报