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?

user36729
  • 545
  • 5
  • 30

1 Answers1

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.

Community
  • 1
  • 1
Kartik
  • 8,347
  • 39
  • 73