Reputation: 185
I have a dataframe that looks like this:
product score
0 1179160 0.424654
1 1066490 0.424509
2 1148126 0.422207
3 1069104 0.420455
4 1069105 0.414603
.. ... ...
491 1160330 0.168784
492 1069098 0.168749
493 1077784 0.168738
494 1193369 0.168703
495 1179741 0.168684
what I'm trying to achieve is to multiply certain score values corresponding to specific products by a constant. I have the products target of this multiplication in a list like this: [1069104, 1069105] (this is just a simplified example, in reality it would be more than two products) and my goal is to obtain this:
Multiply scores corresponding to products 1069104 and 1069105 by 10:
product score
0 1179160 0.424654
1 1066490 0.424509
2 1148126 0.422207
3 1069104 4.204550
4 1069105 4.146030
.. ... ...
491 1160330 0.168784
492 1069098 0.168749
493 1077784 0.168738
494 1193369 0.168703
495 1179741 0.168684
I know that exists DataFrame.multiply but checking the examples it works for full columns, and I just one to change those specific values.
Upvotes: 6
Views: 2673
Reputation: 31
import pandas as pd
# Make data
df = pd.DataFrame({'product': [2, 4, 8, 0],
'score': [0.2, 0.1, 0.2, 0.1]})
# List of products to change
product_list = [8,4]
for product_no in product_list: # Loop though product numbers
product = df.loc[df['product'] == product_no] # Find the product corresponding to given product number
score = product["score"].values[0] # Extract the score for the given product number
print(score*10) # Modify score as you please
df.at[product.index[0], "score"] = score*10 # If you want to modify the dataframe with the new value
print(df)
Upvotes: 0
Reputation: 101
We can use if condition with for loop to multiply the specific values
for i in range (len(df)): `if((df[colun]==1069104) or (df[colun]==1069105)): df[score]=df[score]*10
Upvotes: 0
Reputation: 150745
You can use boolean indexing and isin
:
prod_list = [1069104, 1069105]
df.loc[df['product'].isin(prod_list), 'score'] *= 10
Upvotes: 5
Reputation: 6181
You can use loc
functionality (documentation)-
df = pd.DataFrame([[1, 'a'], [2, 'a'], [3, 'b']], columns=['num', 'c'])
df.loc[df.c == 'a', 'num'] = df.num * 10
Upvotes: 1