Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I overwrite a mapping of a column based on its current value and value of two other columns?

I have the following pandas dataframe

is_and_mp    market_state       reason     
  '100'          None             NaN  
  '400'          None             NaN 
  '100'          ALGO             NaN
  '400'          OPENING          NaN

I want to write two mappings where if is_and_mp is either '100' or '400', and market_state == None and reason == NaN, then map market_state =CONTINUOUS_TRADING.

So the output would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

is_and_mp         market_state              reason     
  '100'        CONTINUOUS_TRADING             NaN  
  '400'        CONTINUOUS_TRADING             NaN
  '100'             ALGO                      NaN
  '400'           OPENING                     NaN

It is important for the existing mappings not to change! Thanks

>Solution :

Use DataFrame.loc with chained mask by & for bitwise AND:

df.loc[df.is_and_mp.isin([ '100', '400']) & df.market_state.isna() & df. reason.isna(),  'market_stat'] = 'CONTINUOUS_TRADING'

or if values are numeric:

df.loc[df.is_and_mp.isin([ 100, 400]) & df.market_state.isna() & df. reason.isna(),  'market_stat'] = 'CONTINUOUS_TRADING' 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading