Philip Southwell
Philip Southwell

Reputation: 385

Convert a single string formatted as a csv file into a pandas dataframe

I have an extremely long single python string which is formatted as a csv file. A shortened version looks like this.

"1,1,6;3,6,2;3,3,1;"

How could I turn this into a pandas DataFrame?

Upvotes: 3

Views: 1660

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210982

UPDATE: - using lineterminator parameter makes it very simple:

In [77]: pd.read_csv(io.StringIO('1,1,6;3,6,2;3,3,1;'), lineterminator=';', header=None)
Out[77]:
   0  1  2
0  1  1  6
1  3  6  2
2  3  3  1

OLD answer:

import io
import pandas as pd

df = pd.read_csv(io.StringIO('\n'.join("1,1,6;3,6,2;3,3,1;".split(';'))), header=None)

print(df)

Output:

   0  1  2
0  1  1  6
1  3  6  2
2  3  3  1

Upvotes: 8

Related Questions