kamome
kamome

Reputation: 858

split multiple columns by separator pandas

How to split every column by ":", using pandas

    ,0,1,2,3,4
0,MMSI : 222111345,Country : Singa,Ship name : xxxVessel,Call sign : abcd,IMO number : 12345
1,MMSI : 222111345,Country : Singa,Ship name : xxxVessel,Call sign : abcd,IMO number : 12345
2,MMSI : 222111345,Country : Singa,Ship name : xxxVessel,Call sign : abcd,IMO number : 12345
3,MMSI : 222111345,Country : Singa,Ship name : xxxVessel,Call sign : abcd,IMO number : 12345

I tryed df3 = df3[df3.columns[0]].str.split(":",expand=True) but doesn´t work

Upvotes: 0

Views: 83

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24314

You can try via concat() and list comprehension:

df=pd.concat([df3[x].str.split(':',expand=True) for x in df3],axis=1)

Note: If there are integer and float values in columns then:

cols=df3.columns[df3.dtypes=='O']
#Filtered out columns that are of type Object    
df=pd.concat([df3[x].str.split(':',expand=True) for x in cols],axis=1)

Note:

If you are reading csv file then you can also try this :

df3=pd.read_csv("filename.csv", sep=",|:").reset_index()

Upvotes: 1

Related Questions