0

I have simple task but it seems to be evading me on how to work it out, I have searched and found the groupby function but it did not work for me hence the post. In short - I have two columns 'Code' & 'Adjusted Cost' in a CSV file. I would like to sum all costs associated with the unique Code (codes identified from numbers 1.1 - 5.15). I am trying df.loc but still no luck.

df['Multiplier'] = df['Code'].map(multipliers)
df['Adjusted Qty'] = df['Quantity'] * df['Multiplier']
        
df['Adjusted Cost'] = df['Adjusted Qty'] * df['Rate']
df['Total'] = df['Quantity'] * df['Rate']
df['Sqm Cost'] = df['Adjusted Cost'] / gifa

df['Sqm Total Cost'] = df['Sqm Cost'].sum()    
    
total = df['Adjusted Cost'].sum() #totals the entire 'Adjusted Cost Column'

nrm =  df.loc[:1.1, 'Adjusted Cost'].sum()

Edit:

Please see attached CSV snippet CSV File

I would like to total the 'Adjusted Cost' column by 'Code' and store it in a variable called 'nrm'. For example in the attached example, 1.1 would total '2500' and 2.4 would total '1100'.

Further edit:

I try the groupby function by using: nrm = df.groupby(['Code']).sum(df['Adjusted Cost'])

Sorry for not been clear I'm very new to pandas and python. The main issue I have with groupby is telling it which Code to look for and which Column to total.

  • This post could help https://stackoverflow.com/questions/37947641/pandas-how-to-sum-columns-based-on-conditional-of-other-column-values – Richard Mar 04 '22 at 23:05
  • 1
    Please have a look at [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and [edit] your question with a sample of you rinput data and your expected output based on that input so that we can better understand your query. Also please describe _how_ your previous attempt was wrong; "it did not work for me " What specifically did you try, and why was it not correct? – G. Anderson Mar 04 '22 at 23:27
  • Agree with @G.Anderson, please provide a simple example dataframe with a few rows and 'Code' & 'Adjusted Cost' columns, then provide the output you're expecting from this simple input df, and I'm sure we can help. Sounds like you need to use `groupby`, but need more context – frederick-douglas-pearce Mar 05 '22 at 00:05
  • if `groupby` didn't work then you could describe it - and maybe we could fix it. I think you should use `groupby("Code")` for this. You can't do this with `loc` – furas Mar 05 '22 at 00:18
  • better add some example data in code (as `DataFrame(...)`) and show what result you get and what result you expect. – furas Mar 05 '22 at 00:19
  • you want to sum by unique `Code` but you doesn't use column `Code` in your question. – furas Mar 05 '22 at 00:22
  • df.groupby('Code')['Adjusted Cost'].sum() – Raymond Kwok Mar 05 '22 at 01:43

0 Answers0