Create Pandas DataFrame from a string Create Pandas DataFrame from a string python python

Create Pandas DataFrame from a string


A simple way to do this is to use StringIO.StringIO (python2) or io.StringIO (python3) and pass that to the pandas.read_csv function. E.g:

import sysif sys.version_info[0] < 3:     from StringIO import StringIOelse:    from io import StringIOimport pandas as pdTESTDATA = StringIO("""col1;col2;col3    1;4.4;99    2;4.5;200    3;4.7;65    4;3.2;140    """)df = pd.read_csv(TESTDATA, sep=";")


Split Method

data = input_stringdf = pd.DataFrame([x.split(';') for x in data.split('\n')])print(df)


In one line, but first import IO

import pandas as pdimport io   TESTDATA="""col1;col2;col31;4.4;992;4.5;2003;4.7;654;3.2;140"""df = pd.read_csv(io.StringIO(TESTDATA), sep=";")print(df)


matomo