How to Import a Data Frame from a String Using Pandas
Background
When testing various functionalities, users may need to create a DataFrame from a string. This tutorial demonstrates a straightforward method for achieving this.
Solution
To create a DataFrame from a string, the StringIO module can be employed. Here's a step-by-step guide:
import sys if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO import pandas as pd
Replace sys.version_info[0] with 3 for Python 3 or 2 for Python 2.
TESTDATA = StringIO("""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """)
Replace the contents of the triple quotes with your test data.
df = pd.read_csv(TESTDATA, sep=";")
This creates a DataFrame df with semicolon-separated columns.
By following these steps, users can conveniently create a DataFrame from a string, regardless of Python version.
The above is the detailed content of How Can I Create a Pandas DataFrame from a String?. For more information, please follow other related articles on the PHP Chinese website!