Python: convert str object to dataframe

Question:

I have a string object as follows:

time,exchange,fsym,tsym,close,high,low,open,volumefrom,volumeto
1660003200,NYSE,BTC,USD,100.1,103,99.1,100,30,10000
1660003260,NYSE,BTC,USD,101.3,104,100.1,102,39,12000
1660003320,NYSE,BTC,USD,100.9,103.2,98,100,32,100230

I am trying to convert this string object to a DataFrame. I have tried adding brackets "[]" around the data but that still didn’t work. Any suggestions would be greatly appreciated.

Asked By: MathMan 99

||

Answers:

Looks like your string is in CSV format. You can convert this into a Pandas data frame using the StringIO module:

from io import StringIO
import pandas as pd

data = StringIO("""time,exchange,fsym,tsym,close,high,low,open,volumefrom,volumeto
1660003200,NYSE,BTC,USD,100.1,103,99.1,100,30,10000
1660003260,NYSE,BTC,USD,101.3,104,100.1,102,39,12000
1660003320,NYSE,BTC,USD,100.9,103.2,98,100,32,100230""")

df = pd.read_csv(data)
print(df)
Answered By: Prins
import pandas as pd

string = """time,exchange,fsym,tsym,close,high,low,open,volumefrom,volumeto
1660003200,NYSE,BTC,USD,100.1,103,99.1,100,30,10000
1660003260,NYSE,BTC,USD,101.3,104,100.1,102,39,12000
1660003320,NYSE,BTC,USD,100.9,103.2,98,100,32,100230"""

str_list_with_comma = string.split("n")
columns = []
data = []
for idx, item in enumerate(str_list_with_comma):
    if(idx == 0):
        columns = item.split(",")
    else:
        data.append(item.split(","))

df = pd.DataFrame(data, columns=columns)
print(df)

Output:


         time exchange fsym tsym  close   high    low open volumefrom volumeto
0  1660003200     NYSE  BTC  USD  100.1    103   99.1  100         30    10000
1  1660003260     NYSE  BTC  USD  101.3    104  100.1  102         39    12000
2  1660003320     NYSE  BTC  USD  100.9  103.2     98  100         32   100230
Answered By: uozcan12
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.