Search code examples
pythonpandascsvexport-to-csv

How to append data from one CSV column to another in Python


I have the following CSV file output:

Customer,Misc
customer1,business-dns-test2
customer2,dns-test2
customer1,dns-test1

The goal at hand is to append customer1 the string -business only if the word is present in the same row under Misc.

That is, I am looking for the final CSV output to be:

Customer,Misc
customer1-business,dns-test2
customer2,dns-test2
customer1,dns-test1

Essentially, the keyword here is business. I need to make sure customer1 and customer1-business are treated as separate customers despite them sharing the same name customer1.

Thoughts?


Solution

  • We can do

    df.loc[df.Misc.str.startswith('business'),'Customer']+='-business'
    df.Misc=df.Misc.str.strip('business-')
    df
    Out[93]: 
                 Customer       Misc
    0  customer1-business  dns-test2
    1           customer2  dns-test2
    2           customer1  dns-test1