Home >Backend Development >Python Tutorial >How to Convert a String to a Pandas DataFrame in Python?
In the context of testing software functionality, creating a DataFrame from a string is a common requirement. Consider the following sample data:
TESTDATA="""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """
Solution:
To efficiently convert this string into a Pandas DataFrame, the following steps can be implemented:
import sys if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO TESTDATA = StringIO("""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """)
import pandas as pd df = pd.read_csv(TESTDATA, sep=";")
Explanation:
The StringIO module provides a convenient way to handle strings as file-like objects. By passing this object to pandas.read_csv, we can read the data from the string into a DataFrame. Specifying the separator ";" ensures that the columns are correctly parsed.
This approach offers a straightforward and efficient method for creating a DataFrame from a string, making it suitable for various testing scenarios.
The above is the detailed content of How to Convert a String to a Pandas DataFrame in Python?. For more information, please follow other related articles on the PHP Chinese website!