How do I use Python to split a csv into multiple columns?
(using split function using python)
Expected Output
Run code snippetCopy snippet to answerExpand snippet
I am trying to split a specific column of csv into multiple column and then appending the split values at the end of each row.
I wanted to split second column on ',' and '.' and ';' and then append to each row respective values.
Here is the link to input file(Meta_D1.tx t) and expected output file (Meta_D1.xlsx) I wanted to do it using python, I did it using excel.
Can someone guide me further?
python
(using split function using python)
Code:
"CUSTOMERID","DESCRIPTION","FARE","GUESTS","SEATCLASS","SUCCESS" "1","Braund, Mr. Owen Harris;22","7.25","1","3","0" "2","Cumings, Mrs. John Bradley (Florence Briggs Thayer);38","71.2833","1","1","1" "3","Heikkinen, Miss. Laina;26","7.925","0","3","1" "4","Futrelle, Mrs. Jacques Heath (Lily May Peel);35","53.1","1","1","1" "5","Allen, Mr. William Henry;35","8.05","0","3","0" "6","Moran, Mr. James;","8.4583","0","3","0" "7","McCarthy, Mr. Timothy J;54","51.8625","0","1","0" "8","Palsson, Master. Gosta Leonard;2","21.075","3","3","0" "9","Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg);27","11.1333","0","3","1" "10","Nasser, Mrs. Nicholas (Adele Achem);14","30.0708","1","2","1" "11","Sandstrom, Miss. Marguerite Rut;4","16.7","1","3","1" "12","Bonnell, Miss. Elizabeth;58","26.55","0","1","1" "13","Saundercock, Mr. William Henry;20","8.05","0","3","0" "14","Andersson, Mr. Anders Johan;39","31.275","1","3","0" "15","Vestrom, Miss. Hulda Amanda Adolfina;14","7.8542","0","3","0"
Expected Output
Code:
_CUSTOMERID _DESCRIPTION Prefix Name Age _FARE _GUESTS _SEATCLASS _SUCCESS 1 Braund Mr Owen Harris 22 7.25 1 3 0 2 Cumings Mrs John Bradley (Florence Briggs Thayer) 38 71.2833 1 1 1 3 Heikkinen Miss Laina 26 7.925 0 3 1 4 Futrelle Mrs Jacques Heath (Lily May Peel) 35 53.1 1 1 1 5 Allen Mr William Henry 35 8.05 0 3 0 7 McCarthy Mr Timothy J 54 51.8625 0 1 0 8 Palsson Master Gosta Leonard 2 21.075 3 3 0 9 Johnson Mrs Oscar W (Elisabeth Vilhelmina Berg) 27 11.1333 0 3 1 10 Nasser Mrs Nicholas (Adele Achem) 14 30.0708 1 2 1 11 Sandstrom Miss Marguerite Rut 4 16.7 1 3 1 12 Bonnell Miss Elizabeth 58 26.55 0 1 1 13 Saundercock Mr William Henry 20 8.05 0 3 0 14 Andersson Mr Anders Johan 39 31.275 1 3 0 15 Vestrom Miss Hulda Amanda Adolfina 14 7.8542 0 3 0
I am trying to split a specific column of csv into multiple column and then appending the split values at the end of each row.
I wanted to split second column on ',' and '.' and ';' and then append to each row respective values.
Code:
`enter code here`
import csv
fOpen1=open('Meta_D1.txt')
reader=csv.reader(fOpen1)
mylist=[elem[1].split(',') for elem in reader]
mylist1=[]
for elem in mylist:
mylist1.append(elem)
#writing to a csv file
with open('out1.csv', 'wb') as fp:
myf = csv.writer(fp, delimiter=',')
myf.writerows(mylist1)
Run code
Can someone guide me further?
python