Home >Backend Development >Python Tutorial >How to Parse a String into a Pandas DataFrame in Python?

How to Parse a String into a Pandas DataFrame in Python?

DDD
DDDOriginal
2024-12-01 02:30:10144browse

How to Parse a String into a Pandas DataFrame in Python?

Parsing a String into a Pandas DataFrame

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!

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