Search code examples
pythoncsvexport-to-csv

How to capture specific info from CSV column in python


I have a CSV file that has a table with information that I'd like to reference in another table. To give you a better perspective, I have the following example:

"ID","Name","Flavor"
"45fc754d-6a9b-4bde-b7ad-be91ae60f582","account1-test1","m1.medium"
"83dbc739-e436-4c9f-a561-c5b40a3a6da5","account3-test2","m1.tiny"
"ef68fcf3-f624-416d-a59b-bb8f1aa2a769","account1-test3","m1.medium"

I would like to add another column that references the Name column and pulls the customner name in one column and the rest of the info into another column, example:

"ID","Name","Flavor","Customer","Misc"
"45fc754d-6a9b-4bde-b7ad-be91ae60f582","account1-test1","m1.medium","account1","test1"
"83dbc739-e436-4c9f-a561-c5b40a3a6da5","account3-test2","m1.tiny","account3,"test2"
"ef68fcf3-f624-416d-a59b-bb8f1aa2a769","account1-test3","m1.medium","account1","test3"

The task here is to have a python script that opens the original CSV file, and creates a new CSV file with the added column. Any ideas? I've been having trouble parsing through the name column successfully.


Solution

  • data = pd.read_csv('your_file.csv')
    data[['Customer','Misc']] = data.Name.str.split("-",expand=True) 
    

    Now you can again save it to csv file by :

    data.to_csv('another_file.csv')