1
ce["Buy_Price"] = ce["Trade_price"][ce["Trade_type"] == "CE Buy"]

How to use loc in this line to avoid warning........."A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

2 Answers2

0

If you want to give "Buy_Price" the value of "Trade_price" when [ce["Trade_type"] == "CE Buy"] you can use np.where:

import numpy as np
ce["Buy_Price"] = np.where(ce["Trade_type"] == "CE Buy", ce["Trade_price"], ce["Buy_Price"])

If you still want to use .loc:

ce.loc[ce['Trade_type']=='CE Buy','Buy_Price'] = ce['Trade_price']

Regarding your followup question about: ce = df[(df["Trade_type"] == "CE Buy") | (df["Trade_type"] == "CE Sell")]: This code should work ok. However, you can make it better like:

types = ['CE Sell', 'CE Buy']
ce = df[df['Trade_type'].isin(types)]
gtomer
  • 5,643
  • 1
  • 10
  • 21
  • all are giving correct answers but as well as all are throwing same – Arunava Datta Aug 31 '22 at 08:51
  • The first one - using 'where' cannot give the same. The second one - on my dataframe does not. – gtomer Aug 31 '22 at 08:52
  • Please post the result of 'ce.dtypes' – gtomer Aug 31 '22 at 08:52
  • Datetime object Symbol object Trade_price float64 Trade_type object Buy_Price float64 Sell_Price float64 P/L float64 dtype: object – Arunava Datta Aug 31 '22 at 09:02
  • This is all fine. Wou should not have any problem with my answer above – gtomer Aug 31 '22 at 09:03
  • @gtomer..i located the error..it was showing for........ ce = df[(df["Trade_type"] == "CE Buy") | (df["Trade_type"] == "CE Sell")] ..how can i solve this also?? – Arunava Datta Aug 31 '22 at 09:09
  • See above updated answer. However, the new line that you posted should not give you an error either – gtomer Aug 31 '22 at 09:14
  • @gtomer it would give the error as ce is a slice of df, the error is saying that you're trying to make changes to slice of the original database, rather than a copy of it which can cause unwanted results. If you add `.copy()` on to the end of the df filter, the errors should go :) – Emi OB Aug 31 '22 at 09:19
0

you should use .loc in this way to correct the warning.

ce["Buy_Price"] = ce.loc[:]["Trade_price"][ce["Trade_type"] == "CE Buy"]

in general:

df['new_column_name'] = df.loc[:][old_column_name][boolean condition]

Sadegh Pouriyan
  • 157
  • 1
  • 10