'Using pandas how to add(math operations) multiple rows between two columns to get a total [closed]
I have a csv file with multiple columns that represent office supplies sales. I want to find the total sales for pens (unit price and item are the two columns) so firstly I sorted the df to search for pens under the column item and listed its unit price. now I cant figure out how to add all of the unit prices for each pen sale. how would I do it?
Solution 1:[1]
I think there is a slight flaw in the logic you presented, but it is hard without the full context - i.e. sample dataframe, code snippet, etc.
In order to calculate total sales of pen items you would need to calculate the sum(price * quantity) of all sales.
so simple df:
import pandas as pd
df = pd.DataFrame(
{
'item': ['pen', 'pen', 'chair'],
'price':[5, 5, 10],
'qtt': [1, 1, 1]
}
)
sales = sum(df.loc[df['item']=='pen', 'price'] * df.loc[df['item']=='pen', 'qtt'])
learning to deal with slicing is key. https://pandas.pydata.org/docs/user_guide/indexing.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | the-marcos |
