I am trying to add a column to my dataframe that calculates Delta. Based on the name in the column 'Name', if that name is in the list, it will calculate df['A'] - df['B'], if the name is not in the list, calculation is df['B'] - df['A'].
Here is what I have:
for i in list1:
df['Delta'] = np.where(df['Name'] == i, np.maximum(0, df['A'] - df['B']), np.maximum(0, df['B'] - df['A']))
The problem is that it goes trough each i separately and rewrites all the i's it did before.
How can i rewrite this code, so that it doesn't go through each i, but instead just checks if df['Name'] equals to any of the i's?
Something like:
df['Delta'] = np.where(df['Name'] == any(list1), np.maximum(0, df['A'] - df['B']), np.maximum(0, df['B'] - df['A']))
If there is an overall better way to do this, please let me know.