2

Is there a way to add or subtract to an existing dataframe?

For example, given the code below:

import pandas as pd
Apple= pd.DataFrame({'Product':['MacBook', 'iPhone', 'iPad', 'Apple Watch'],
                        'Inventory':['999', '333', '666', '190']})

Is there a way to add 150 to an existing inventory so that the number of Apple Watches is 340?

2
  • 1
    Apple.loc[Apple.Product.eq('Apple Watch'), 'Inventory'] += 150 Commented Sep 1, 2018 at 16:57
  • @VanPeer you should avoid that, as it's chained indexing, which is discouraged in pandas Commented Sep 1, 2018 at 16:57

3 Answers 3

1

Use loc along with a boolean selection to update the column:

Apple.loc[Apple.Product.eq('Apple Watch'), 'Inventory'] += 150

       Product  Inventory
0      MacBook        999
1       iPhone        333
2         iPad        666
3  Apple Watch        340

In the example you've provided in your question, Inventory contains strings. If this is the same in your actual data, you need to cast to int first:

Apple.Inventory = Apple.Inventory.astype(int)
Sign up to request clarification or add additional context in comments.

Comments

0

First convert your series of strings to an int series:

df['Inventory'] = df['Inventory'].astype(int)

You can then use pd.DataFrame.loc:

df.loc[df['Product'] == 'Apple Watch', 'Inventory'] += 150

Alternatively, you can make Product your index and then update:

df = df.set_index('Product')
df.loc['Apple Watch', 'Inventory'] += 150

Using either method, if you have multiple products with the same name, their inventory will each be increased by 150.

Comments

0

if you define your items as int , you can do it this way:

import pandas as pd
Apple= pd.DataFrame({'Product':['MacBook', 'iPhone', 'iPad', 'Apple Watch'],
                        'Inventory':['999', '333', '666', 190]})

Apple.Inventory[Apple.Product == 'Apple Watch'] += 150
print(Apple)

Comments

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.