title: How to calculate the cost of goods sold
body: <p>With this code below my out put  tells me how many products in that batch have not been shipped out</p>
  <p>However, I want to know the cost of each product sold in the first-out rule.</p>
  <pre><code>import pandas as pd
  import numpy as np
  
  df=pd.DataFrame({'code': [2,2,2,2,2,2,2,3,3,3,5,5,6],
          'date': ['2015-11-15','2015-11-17','2015-11-20','2016-04-01','2016-04-02','2016-04-03','2016-11-01','2015-02-01','2015-05-01','2016-03-01','2015-11-20','2016-06-01','2015-02-01'],
          'num' : [10,-10, 20, 10, -30,50, -40, 25, 35, -15, 50, -50, 35],
          'price': [3.8,3.7,3.5,3.2, 3.6,3.4, 3.5, 7, 7.5,  8, 5,  5.5, 11.5],
          'money': [-38,37,-70,-32, 108,-170, 140,-175,-262.5,120,-250, 275,-402.5]
          })
  print(df)
  
  def FiFo(dfg):
      if dfg[dfg['CS'] &lt; 0]['num'].count():
          subT = dfg[dfg['CS'] &lt; 0]['CS'].iloc[-1]
          dfg['num1'] = np.where((dfg['CS'] + subT) &lt;= 0, 0, dfg['CS'] + subT)
          dfg['num1'] = np.where(dfg['num']&lt;dfg['num1'],dfg['num'],dfg['num1'])
          dfg['num'] = np.where(dfg['num1']&gt;0,dfg['num1'],0)
      return dfg
  
  df['PN'] = np.where(df['num'] &gt; 0, 'P', 'N')
  df['CS'] = df.groupby(['code', 'PN'])['num'].cumsum()
  dfR = df.groupby(['code'], as_index=False)\
      .apply(FiFo) \
      .drop(['price','PN'], axis=1) \
      .reset_index(drop=True)
  
  print(dfR[dfR['num'] &gt; 0])
  </code></pre>
  <pre>
  2015-11-17: The cost of sold product 2 is 3.8
  2016-04-02: The cost of sold product 2 is (70+32)/(20+10)=3.4
  </pre>