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"
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"
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)]
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]