Categories
Python Answers

How to create Pandas DataFrame from a string with Python?

Spread the love

Sometimes, we want to create Pandas DataFrame from a string with Python.

In this article, we’ll look at how to create Pandas DataFrame from a string with Python.

How to create Pandas DataFrame from a string with Python?

To create Pandas DataFrame from a string with Python, we can use the StringIO module.

For instance, we write:

from io import StringIO
import pandas as pd

TESTDATA = 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=";")
print(df)

We have the TESTDATA string with some CSV test data.

Then we call read_csv with TESTDATA to read the string into a DataFrame.

We set the sep parameter to set the separator used by the CSV string so the data will parse correctly.

Therefore, df is:

   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

Conclusion

To create Pandas DataFrame from a string with Python, we can use the StringIO module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *