Huzefa Sadikot
Huzefa Sadikot

Reputation: 581

Adding a column in pandas dataframe based on a condition

PFA the df

DF

In this I want to add a column traded_value as:

  1. If the order_type = Market then orders['traded_value]= orders['average_price] * quantity
  2. If the order_type = Limit then orders['traded_value]= orders['price] * quantity

The code to get the above df is as follows:

orders=pd.read_csv('C:/Users/hozef/OneDrive/Desktop/orders.csv')
orders.drop(['parent_order_id', 'status_message', 'status_message_raw', 'meta', 'tag', 'exchange_timestamp',
             'exchange_update_timestamp', 'disclosed_quantity', 'market_protection', 'trigger_price', 'guid','order_id','exchange_order_id'], axis=1,
            inplace=True)
orders=pd.read_csv()
orders['System_Price'] = np.where(orders['order_type'] == 'MARKET',
                                         orders['average_price'] * 1, 'nan')

orders['System_Target_Price'] = np.where(orders['order_type'] == 'LIMIT',
                                         orders['price'] * 1, 'nan')

conditions = [
    (orders['transaction_type'] == 'BUY'),
    (orders['transaction_type'] == 'SELL')
]
values = ['Target', 'Regular']
orders['Classification'] = np.select(conditions, values)

conditions1 = [
    (orders['transaction_type'] == 'BUY'),
    (orders['transaction_type'] == 'SELL')
]
values1 = ['Bullish', 'Bearish']
orders['trend'] = np.select(conditions1, values1)

Upvotes: 0

Views: 30

Answers (1)

tdy
tdy

Reputation: 41327

If MARKET and LIMIT are the only two order_type, then you can use a single np.where():

orders['traded_value'] = np.where(
    orders['order_type'] == 'MARKET',
    orders['average_price'] * quantity,
    orders['price'] * quantity)

Upvotes: 1

Related Questions