Search code examples
pythonpandasfor-loopdataframenested-loops

run a for loop by traversing on duplicates in the index column: python


I am an amateur user of python and want to develop a logic to find out the orders which can be satisfied from the quantity available related to the parts.

partno  ordernumber orderqty    Qty available
A        abc          15        20
A        acb           5        20
A        adc           8        20
B        a41           9        60
B        a14          16        60
B        a56          30        60

there are unique order numbers with order qty for the respective part number. the qty available is the total qty available corresponding to the part number.

I want to find out the orders which can be satisfied from the qty available of the part associated. the output will look something like following

partno  ordernumber orderqty    Qty available  Y/N
A        abc          15        20              Y
A        acb           5        20              Y
A        adc           8        20              N
B        a41           9        60              Y
B        a14          16        60              Y
B        a56          30        60              Y

I am struggling to write a for loop which will traverse on the duplicate part numbers and reduce the orderqty from qty available everytimme it iterates on order number.

psuedo code:

      for partno in df
      for ordernumber in df.interrow
      if (qtyavailble>orderqty) 
      {df.newcoln = "Y" & qtyavailable = qtyavailable-orderqty}
      else {df.newcoln="N"}

I know it's a horrible code but you get the idea. Thanks!


Solution

  • You can groupby partno then do cumsum for orderqty, and to find whether it is greater than the Qtyavailable

    df.groupby('partno').orderqty.cumsum().le(df.Qtyavailable).map({True:'Y',False:'N'})
    Out[459]: 
    0    Y
    1    Y
    2    N
    3    Y
    4    Y
    5    Y
    dtype: object