How can I add conditional logic to fill certain rows of a dataframe with certain strings when certain conditions are met?

Question:

I am trying to write some Python logic to fill a csv file/pandas dataframe table called (table) with certain conditions, but I can’t seem to get it to do what I want.

I have two columns in table: 1. trade_type and 2. execution_venue.

Conditional statement I want to write in Python:

The execution_venue entry will only be filled with either AQXE or AQEU, depending on the trade_type.

When the trade_type is filled with the string DARK, I want the the execution_venue to be filled with XUBS (if it was filled with AQXE before), and AQED (if it was filled with AQEU before).

Here is my code to do this:

security_mic = ('AQXE', 'AQEU')
table.loc[table['trade_type'] == 'DARK', 'execution_venue'] = {'AQXE': 'XUBS',
                                                                               'AQEU': 'AQED'}.get(security_mic)

When I replace the right hand side of the equality with a string test, I am getting the same error, so I suspect the error is to do with the left hand side, in that it is not accessing the correct place in the dataframe!

Asked By: Patrick Chong

||

Answers:

Lets use replace for substitution of old values where trade_type os DARK

d = {'AQXE': 'XUBS', 'AQEU': 'AQED'}
table.loc[table['trade_type'] == 'DARK', 'execution_venue'] = table['execution_venue'].replace(d)
Answered By: Shubham Sharma
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.