Skip to content
Advertisement

Splitting strings containing newline command and outputting to two columns

A minimal example of my data looks as follows:

JavaScript

I am looking for a way (using pandas, preferably) to:

  1. identify rows in which the address column contains “C/O”, and
  2. split the string at the newline (n) command and output the part of the string before the newline command to the corresponding row in the coaddress column and keep the part of the string after the newline command in the address column.

The df I want to achieve looks as follows:

JavaScript

Any suggestions on how to achieve this? Thanks!

Advertisement

Answer

We can do it in full Pandas using loc, contains and split like so :

JavaScript

Output :

JavaScript

UPDATE :

As commented by @Neither, we can avoid some repetition by setting a function here :

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