0

I have a data frame in pandas as follows:

  A    B    C    D
  3    4    3    1
  5    2    2    2
  2    1    4    3

My final goal is to produce some constraints for an optimization problem using the information in each row of this data frame so I don't want to generate an output and add it to the data frame. The way that I have done that is as below:

def Computation(row):

    App = pd.Series(row['A'])

    App = App.tolist()

    PT = [row['B']] * len(App)

    CS = [row['C']] * len(App)

    DS = [row['D']] * len(App)

    File3 = tuplelist(zip(PT,CS,DS,App))

    return m.addConstr(quicksum(y[r,c,d,a] for r,c,d,a in File3) == 1)

But it does not work out by calling:

df.apply(Computation, axis = 1)

Could you please let me know if there is anyway to do this process?

1
  • m is defined for the interface of python and an optimization software. .iterrows works for me. Thanks! Commented Sep 24, 2016 at 17:32

1 Answer 1

1

.apply will attempt to convert the value returned by the function to a pandas Series or DataFrame. So, if that is not your goal, you are better off using .iterrows:

# In pseudocode:
for row in df.iterrows:
    constrained = Computation(row)

Also, your Computation can be expressed as:

def Computation(row):
    App = list(row['A']) # Will work as long as row['A'] is iterable

    # For the next 3 lines, see note below.
    PT = [row['B']] * len(App)
    CS = [row['C']] * len(App)
    DS = [row['D']] * len(App)

    File3 = tuplelist(zip(PT,CS,DS,App))
    return m.addConstr(quicksum(y[r,c,d,a] for r,c,d,a in File3) == 1)

Note: [<list>] * n will create n pointers or references to the same <list>, not n independent lists. Changes to one copy of n will change all copies in n. If that is not what you want, use a function. See this question and it's answers for details. Specifically, this answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.