0

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

1
  • Why dont you use separator as df = pd.read_csv("test_data1", header=None, sep=":") while you reading the file itself? Commented Jul 2, 2021 at 10:07

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.