Skip to content
Advertisement

How can I use python conditionals to map columns in a dataframe with duplicates in them?

I am trying to create a mapping where there are duplicates in certain columns in a dataframe.

Here are two examples of dataframes I am working with:

JavaScript

Here is what I need; 3 conditional python logic that does:

  • when we see the first issue_status of 100 and trading_state of None, map F in the reason column.
  • when we see the second last issue_status of 400 and trading_state of None, map SL in the reason column.
  • when we see the last issue_status of 400 and trading_state of None, map L in the reason column.

Here is another example:

JavaScript

@jezrael, I am getting the following error, for your last line of code (market_info_df1['reason'] = s1.combine_first(s2)):

JavaScript

Any idea what is causing this?

Advertisement

Answer

You can filter by 400 and None values for df1, create helper Series with range and mapping last and second last values, for first 100 and None values use Series.duplicated, last join both Series by Series.combine_first:

JavaScript

For second:

JavaScript

If necessary empty strings in reason column use:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement