How to convert a list of text string to a pandas dataframe in python?

Viewed 144

I have a list of text strings that represents rows and columns and I want to convert it to a pandas dataframe.

Right now I use copy-paste of the text to an editor, then save it as a csv file and then read it using pd.read_csv(). I am certain though that this can be automated somehow.

For a reproducible example, consider the following list:

  ['Symbol,Description,Qty,Trade Price,Mark,Mark Value,P/L Day,P/L Open,P/L ', 'AXTI,AXT INC COM,+90,10.79,9.46,851.40,0.00,-119.70,-12.33', 'INTT,INTEST CORP COM,+50,5.64,5.02,251.00,0.00,-31.00,-10.99', 'ACMR,ACM RESEARCH INC COM CL A,+201,80.9374,73.20,14713.20,0.00,-1,555.21,-9.56', 'ASUR,ASURE SOFTWARE INC COM,+90,7.70,7.20,648.00,0.00,-45.00,-6.49']
2 Answers

Try:

import io
import pandas as pd
df  = pd.read_csv(io.StringIO("""
Symbol,Description,Qty,Trade Price,Mark,Mark Value,P/L Day,P/L Open,P/L 
AXTI,AXT INC COM,+90,10.79,9.46,851.40,0.00,(119.70),-12.33
INTT,INTEST CORP COM,+50,5.64,5.02,251.00,0.00,(31.00),-10.99
ACMR,ACM RESEARCH INC COM CL A,+201,80.9374,73.20,14713.20,0.00,(1555.21),-9.56
ASUR,ASURE SOFTWARE INC COM,+90,7.70,7.20,648.00,0.00,(45.00),-6.49
"""), sep=r",", engine="python") 

Prints:

 Symbol                Description  Qty  Trade Price   Mark  Mark Value  \
0   AXTI                AXT INC COM   90      10.7900   9.46       851.4   
1   INTT            INTEST CORP COM   50       5.6400   5.02       251.0   
2   ACMR  ACM RESEARCH INC COM CL A  201      80.9374  73.20     14713.2   
3   ASUR     ASURE SOFTWARE INC COM   90       7.7000   7.20       648.0   

   P/L Day   P/L Open   P/L   
0      0.0   (119.70) -12.33  
1      0.0    (31.00) -10.99  
2      0.0  (1555.21)  -9.56  
3      0.0    (45.00)  -6.49  

Note: We are are using the comma delimiter to parse string. sep=r",". So I had to remove the commas from (1,555.21) for your example.

Try this piece of code:

locatio_to_csv = '../sample.csv'
input_df = pd.read_csv(locatio_to_csv,
                              names=['column_name1', 'column_name2', 'column_name3'..])
Related