Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to convert text into dataframe in python

I am trying to convert a text into a dataframe using Python.

sample_text: 'This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34'

Final Desired output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Steps I am following to achieve above output is listed below :

  1. Break the text into multiple rows and assign it to a variable: I have tried using print() to process this text formatted_text = print('This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34') but it cant be assigned as print() returns NoneType so I get error here.

Desired output after this step:

This is 
sample text

Name|age
--|--
1.abc|45
2.xyz|34
  1. Use above line break text stored in variable to be read as csv with separator | to create dataframe: I have been thinking of processing this as pd.read_csv(formatted_text,sep='|', skipinitialspace=True)

Desired_output after this step:

enter image description here

I tried earlier explaining this problem in SO post but I guess I wasn’t able to explain it well and it got closed. Hope I am able to explain my issue this time. It could be a silly task but I am stuck at this from long now and would appreciated any help.

>Solution :

A possible solution:

text = 'This is \nsample text\n\nName|age\n--|--\n1.abc|45\n2.xyz|34'

pd.read_csv(StringIO(text), lineterminator='\n', engine='c', header=None)

To split the columns:

(pd.read_csv(StringIO(text), lineterminator='\n', engine='c', header=None)[0]
 .str.split(r'|', expand=True))

Output:

             0
0     This is 
1  sample text
2     Name|age
3        --|--
4     1.abc|45
5     2.xyz|34
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading