0

I currently have the following (which is working):

my_dataframe[[new_col_one, new_col_two]] = 
   my_dataframe['col_with_values'].str.extract(some_regex,expand=True)

I would now like to modify the code above based on a column with boolean values called is_true. If is_true contains True it will do the str.extract call. If the is_true column contains False it will place a NaN value in new_col_one and new_col_two.

The is_true has a value for each value in col_with_value. I am not sure how to map them. Should I use a counter/for loop? Is there a better way to achieve it?

Sample output:

col_with_values    is_true    new_col_one    new_col_two
foo                True       f              oo
bar                False      NaN            NaN

1 Answer 1

1

I think you can add mask by boolean column to both sides:

my_dataframe.loc[my_dataframe['is_true'], [new_col_one, new_col_two]] = 
my_dataframe.loc[my_dataframe['is_true'], 'col_with_values'].str.extract(some_regex,expand=True)

Not the answer you're looking for? Browse other questions tagged or ask your own question.