Pandas provides a comprehensive set of data analysis tools for Python users. One common challenge is importing data into a DataFrame from various sources. Strings, in particular, can be a convenient way to store tabular data for testing or other purposes.
If you have a string containing semicolon-separated data like:
TESTDATA="""col1;col2;col3 1;4.4;99 2;4.5;200 3;4.7;65 4;3.2;140 """
You can easily convert it into a Pandas DataFrame by utilizing StringIO, which provides a file-like buffer for strings. The following code demonstrates how to accomplish this:
import pandas as pd 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 """) df = pd.read_csv(TESTDATA, sep=";")
This code uses the pd.read_csv() function to parse the TESTDATA string as a CSV file, treating semicolons as separators. The resulting DataFrame, named df, will contain the structured data from the string.
By leveraging StringIO, you can conveniently operate on strings as if they were file objects, making it easy to import data from diverse sources into Pandas DataFrames for analysis and manipulation.
The above is the detailed content of How Can I Create a Pandas DataFrame from a Semicolon-Separated String in Python?. For more information, please follow other related articles on the PHP Chinese website!