0

I have a dictionary that contains the mean of the price of each product:

{"Apple": 4.50, "Orange": 5.00, 'Banana': 2.00}

What I would like to do is to apply these mean values to rows in my DataFrame that contain a non valid (<=0) value in the "Price" column.

ID Product Price
1 Apple 0
2 Orange -1
1 Banana -1
2 Apple 3.99

I tried to override/change the values by iterating (which I know isn't a good way to do this) and applying the mean value, but I am getting an error SettingWithCopyWarning:

for i in df[df["Price"]<=0].index:
# Row location based on index
  df.loc[i]["Price"] = mean_prices_dict[df.loc[i]["Product"]]
hasan123
  • 5
  • 2

1 Answers1

0

Use Series.map only for filtered rows:

d = {"Apple": 4.50, "Orange": 5.00, 'Banana': 2.00}

mask = df["Price"]<=0
df.loc[mask, 'Price'] = df.loc[mask, 'Product'].map(d)
print (df)
   ID Product  Price
0   1   Apple   4.50
1   2  Orange   5.00
2   1  Banana   2.00
3   2   Apple   3.99
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252