在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)

浙公網安備 33010602011771號