[Solved] How to iterate a vectorized if/else statement over additional columns?


Option 1

You can nest numpy.where statements:

org['LT'] = np.where(org['ID'].isin(ltlist_set), 1,
                     np.where(org['ID2'].isin(ltlist_set), 2, 0))

Option 2

Alternatively, you can use pd.DataFrame.loc sequentially:

org['LT'] = 0  # default value
org.loc[org['ID2'].isin(ltlist_set), 'LT'] = 2
org.loc[org['ID'].isin(ltlist_set), 'LT'] = 1

Option 3

A third option is to use numpy.select:

conditions = [org['ID'].isin(ltlist_set), org['ID2'].isin(ltlist_set)]
values = [1, 2]

org['LT'] = np.select(conditions, values, 0)  # 0 is default value

solved How to iterate a vectorized if/else statement over additional columns?