title: Scipy maximize with constraints
body: <p>The purpose is to find the optimized weight of each factor to maximize a specific value. Scipy only provides optimization to minimize a function so I used a negative sign here to find the maximum value. The codes look ok and scipy can terminate successfully in the end but returned no solution. Can anybody help?</p>
  
  <pre><code>import pandas as pd
  import numpy as np
  from scipy.optimize import minimize
  
  df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
  
  # the sum of weights should be 1.
  cons = ({'type': 'eq',
          'fun' : lambda x: np.array(sum(x)-1)},
          {'type': 'ineq',
          'fun' : lambda x: np.array([a for a in x])})
  
  # wt should be a list like [0.2, 0.3, 0.5]
  def optimizewt(wt):
      s = df[list('ABC')]
      r = df['D']
  
      # rule to calculate the weighted total score of each row
      ts = lambda x: x*wt
  
      # apply the rule to get weighted total scores
      f = ts(s)
      a = f.sum(axis = 1)
  
      # sort the list ascending
      a.sort(ascending=True)
      l = len(a)
  
      # replace the largest and smallest two scores. set others to 0.
      a[0:2] = 1
      a[(l-2):] = -1
      a[2:(l-2)] = 0
  
      # multiply the two lists. return the average of the calculated list.
      return -np.mean(a*r)
  
  res = minimize(optimizewt, [0.5,0.5,0.], constraints=cons)
  
  print(res.x)
  </code></pre>