I am looking for a shorter and more elegant way of writing the condition below, let's say I have 30 different combinations. Is it possible to map some kind of dictionary with multiple conditions or something else?
def set_name(df):
if df['PRODUCT'] == 'A' and df['TYPE'] == 'C2':
return 'AAC2'
elif df['PRODUCT'] == 'A' and df['TYPE'] == 'C3':
return 'AAC3'
elif df['PRODUCT'] == 'B' and df['TYPE'] == 'C2':
return 'BBC"'
df['RETURN'] = df.apply(set_name, axis=1)
Another way is the below which still pretty long if I have many combinations.
conditions = [
(df['PRODUCT'] == 'A') & (df['TYPE'] == 'C2'),
(df['PRODUCT'] == 'A') & (df['TYPE'] == 'C3')
]
values = ['AAC2', 'AAC3']
df['RETURN'] = np.select(conditions, values)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…