0

I have a dataframe transactions with 2 columns source_numberand return_code

I would like to keep the string values of source number whenever the return code is not "successfully completed" and replace it with the string of numbers from return code whenever it is successfully completed.

I came up with this:

if "Successfully completed" in transactions['return_code']: transactions['source_number'] = transactions['return_code'] else: transactions['source_number']

to then remove "|Successfully completed" from the new value in source number but this does not make any modification when I run the script.

Any help is more than welcomed! Thank you

dataframe_pic

  • Can we assume you loaded your data as a `dataframe` with the `pandas` module? – Erfan Feb 25 '19 at 13:06
  • I also tried this without success: `transactions.loc[transactions.return_code.contains('Successfully'), 'source_number'] = transactions.return_code` – Bastien Pb Feb 25 '19 at 13:13
  • @Erfan yes I did indeed – Bastien Pb Feb 25 '19 at 13:18
  • Please check the answer which is suggested, this will answer your question. You want to conditionally replace values. – Erfan Feb 25 '19 at 13:19
  • @Erfan thanks, I tried to refer to it but my problem is that I do not want to replace with a fix value but rather with the value of the second column and I don't know how to do that – Bastien Pb Feb 25 '19 at 13:28
  • The answer is there, please read carefully. You can solve your problem easily with `np.where` from the `numpy` module. This works as following `np.where(condition, value if condition true, value if condition false)` In your case you can refer to values of columns easily with `transactions.source_number` or `transactions.return_code`. – Erfan Feb 25 '19 at 13:32
  • 1
    @Erfan works like a charm! thank you very much – Bastien Pb Feb 25 '19 at 14:32

0 Answers0