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

How to Convert a String to a Pandas DataFrame in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 04:32:14768browse

How to Convert a String to a Pandas DataFrame in Python?

Convert String to Pandas DataFrame

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:

  1. Utilize StringIO for Input Handling:
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
    """)
  1. Invoke Pandas' read_csv Function:
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!

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