0

Suppose i have the data set below. I'm trying to use a pivot table and add a calculated field just like in excel(i.e. Cost/Sales). Here's what i have so far

pd.pivot_table(index="Month",values=["Cost","Sales"] aggfunc='sum')

Month       Type        Cost        Sales
March       A           5           1
June        B           10          2
March       C           10          3
  • 2
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful. – jezrael Aug 26 '18 at 07:05
  • I don't see a question in your post. But if you want to do something like add `Cost` and `Sales` columns, you could do `df['cc'] = df['Cost'] + df['Sales']` assuming you assigned your pivot table to a variable named `df`. – chillin Aug 26 '18 at 07:55
  • Thank you. I want to add for example, Cost / Sales. So, should i put it like this – Benj Cabalona Jr. Aug 26 '18 at 07:59
  • pd.pivot_table(index="Month",values=["Cost","Sales",df['cc'] = df['Cost']/df['Sales'] aggfunc='sum') – Benj Cabalona Jr. Aug 26 '18 at 08:00
  • I think you need to assign your pivot table to a variable first e.g. `df = pd.pivot_table(....` then on the next line, try `df["cost per sale"] = df["Cost"] / df["Sales"]`. – chillin Aug 26 '18 at 08:50
  • Also, I think the first argument given to `pd.pivot_table()` is the DataFrame itself -- assuming `pd` is namespace for pandas and not a DataFrame – chillin Aug 26 '18 at 08:52

0 Answers0