np.where(condition, A, B) - NumPy,
A if condition else B
np.select(conditions, choices) np.where, , .
, , np.select,
import numpy as np
import pandas as pd
df = pd.read_table('data', sep='\s+')
conditions = [S < 0, S > 0]
M, A, B, S = [df[col] for col in 'MABS']
choices = [(M-B).shift(1)*S, (M-A).shift(1)*S]
df['cost'] = np.select(conditions, choices, default=0)
date A B M S cost
0 20150101 8 7 7.5 0 0.0
1 20150101 10 9 9.5 -1 -0.5
2 20150102 9 8 8.5 1 -0.5
3 20150103 11 11 11.0 0 0.0
4 20150104 11 10 10.5 0 0.0
5 20150105 12 10 11.0 -1 -0.5