0

I'm stuck with this assignment:

I received a pd.DataFrame named 'foods' like this:

    foodname      fats
0   Coconut oil   5
1   Grape juice   10

Also I received a pd.Series named 'drinks' like this:

0   Water
1   Grape juice

My task is to create a new column in foods named 'group', then check if foodname is in 'drinks' and if found, set 'group' value as 'drinks'

The final result should look like this:

    foodname      fats  group
0   Coconut oil   5     
1   Grape juice   10    drinks

Then fill empties with 'Misc'

foods.['group'].fillna('Misc', inplace=True)

I have tried:

Create a new empty column with:

foods['group'] = ''

Then, locate if a certain element name is in 'drinks' (this works):

drinks = list(drinks)
foods.iloc[0]['foodname'] in drinks ---> True / False

Then,

for i in list(foods.index):
    if foods.iloc[i]['foodname'] in drinks:
        foods.iloc[i]['group'] = 'drinks'

I get:

A value is trying to be set on a copy of a slice from a DataFrame
IndexError: single positional indexer is out-of-bounds

Other tries:

foods.loc['group'][foods['foodname'] in drinks] = 'drinks'

I would love to know how to deal correctly with this task. I understand that almost every time I am working with views and not with the 'real' DataFrame I think this has to do with this warning but I can't make it work.

Thx in advance! Rgds!

mabatalla
  • 45
  • 10
  • You can also have a look at `isin`, see this [QA](https://stackoverflow.com/questions/45921083/how-to-update-create-column-in-pandas-based-on-values-in-a-list) – Ben.T Jan 11 '22 at 19:26
  • Excellent! That solved my need. I couldn't find the right post. Thx! Should I delete the question?? – mabatalla Jan 12 '22 at 08:32
  • Not necessary, if someone ends up on your question, they can be redirected to the right post with the links :) well written question btw – Ben.T Jan 12 '22 at 12:18

0 Answers0