如果你只有两种选择:
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
例如,
import pandas as pdimport numpy as npdf = pd.Dataframe({'Type':list('ABBC'), 'Set':list('ZZXY')})df['color'] = np.where(df['Set']=='Z', 'green', 'red')print(df)
Set Type color0 Z A green1 Z B green2 X B red3 Y C red
如果你有两个以上的条件,请使用
np.select。例如,如果你想
color成为
yellow
when(df['Set'] == 'Z') & (df['Type'] == 'A')
- otherwise
blue
when(df['Set'] == 'Z') & (df['Type'] == 'B')
- otherwise
purple
when(df['Type'] == 'B')
- otherwise
black
,
然后使用
df = pd.Dataframe({'Type':list('ABBC'), 'Set':list('ZZXY')})conditions = [ (df['Set'] == 'Z') & (df['Type'] == 'A'), (df['Set'] == 'Z') & (df['Type'] == 'B'), (df['Type'] == 'B')]choices = ['yellow', 'blue', 'purple']df['color'] = np.select(conditions, choices, default='black')print(df)
输出:
Set Type color0 Z A yellow1 Z B blue2 X B purple3 Y C black
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)