I am trying to increase the price of on the red pens in this example by 10%. Below is what I have have tried but it increases all the prices once it finds a match
import pandas as pd
df = pd.DataFrame({'item':['red ballpoint pen','red felt tip pen', 'blue ballpoint pen','red eraser',],
'price':[1.50,2.00,1.50,.50]})
for x in df['item']:
if 'red' in x and 'pen' in x:
df['price'] = df['price']*.10 df['price']
I can filter the item column and get the pens but I cannot figure out how to update the price in place without increasing the price on all items
Any help would be greatly appreciated
CodePudding user response:
This will use np.where() to find where both pen and red exist
df['price'] = np.where((df['item'].str.contains('red')) & (df['item'].str.contains('pen')), df['price'] * 1.10, df['price'])
df
CodePudding user response:
Use loc
and str.contains
:
m = df['item'].str.contains('red') & df['item'].str.contains('pen')
df.loc[m, 'price'] *= 1.10
CodePudding user response:
You can just use pandas
to do this in a oneliner:
df.loc[df.item.str.contains('pen') & df.item.str.contains('red'), 'price'] *= 1.1