Home >Backend Development >Python Tutorial >How Can I Create a Pandas DataFrame from a Semicolon-Separated String in Python?

How Can I Create a Pandas DataFrame from a Semicolon-Separated String in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 11:01:10492browse

How Can I Create a Pandas DataFrame from a Semicolon-Separated String in Python?

Reading a Pandas DataFrame from a String

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn