Home >Backend Development >Python Tutorial >How to Parse a String into a Pandas DataFrame in Python?
To facilitate testing, you may encounter the need to parse a string into a Pandas DataFrame.
Let's consider the following test data:
TESTDATA=""";""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """;
Solution:
One straightforward approach to create a DataFrame from a string is to leverage StringIO. This utility allows us to create an in-memory stream object that Pandas can read just like a file. Here's how it's done:
import sys import io 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=";")
This code creates a StringIO object from the TESTDATA string. Depending on your Python version, you may need to use StringIO or io.StringIO. Pandas' read_csv() function then parses the in-memory stream as if it were an actual file, utilizing a semicolon (";") as the field delimiter.
The above is the detailed content of How to Parse a String into a Pandas DataFrame in Python?. For more information, please follow other related articles on the PHP Chinese website!