1

I have started exploring pandas recently, I am trying to import a list of fruits from sector.py and use it as a filter to produce a table of items where only fruits within the list are displayed. I am not getting the output desired is there something wrong with my codes?

Within sector.py

Fruits=['Apple','Orange','Pineapples']

Within calculator.py

import sector
import pandas as pd

pdmart = pd.read_csv('supermarket.csv')
pdextract = pdmart.groupby('item')['price'].sum()

Fruits = pdextract[pdextract.isin(sector.Fruits)]
print Fruits

Current output:

Series([], Name: price, dtype: float64)

Desired output:

Item         Price
Apple        12.0
Orange       7.0
Pineapples   15.0
2
  • 1
    just filter before the groupby, that should do it Commented Sep 28, 2018 at 16:55
  • or reindex with the list after the groupby, which will ensure you display NaN for groups you are missing completely. Commented Sep 28, 2018 at 17:06

1 Answer 1

3

Applying isin on a GroupBy object doesn't make sense. You can use Boolean indexing on the index of your GroupBy object:

Fruits = pdextract[pdextract.index.isin(sector.Fruits)]

You can also filter on a series before your GroupBy operation:

pdextract = pdmart.loc[pdmart['item'].isin(sector.Fruits)]\
                  .groupby('item')['price'].sum()
Sign up to request clarification or add additional context in comments.

6 Comments

Hi! Thank you for your reply, could you explain a little more on why I can't group them before apply isin on the groupings?
@SamT, You can. My first solution is after the GroupBy. Notice pdextract is the GroupBy object as in your question.
cool! thank you! also, if i were to sum up the values of all the fruits, could I do a .sum() again on the variable pdextract? Meaning to say: Fruits 34.0 Apologies if i am vague, this is my first language..
@SamT, Sure, give it a go. But if you have a new question, you should ask a new question. This isn't a forum.
@jpp this is because after doing pdextract = pdmart.groupby('item')['price'].sum() the groupby column becomes the default index column right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.