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

How Can I Create a Pandas DataFrame from a String?

Mary-Kate Olsen
Release: 2024-11-21 07:15:10
Original
595 people have browsed it

How Can I Create a Pandas DataFrame from a String?

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:

  1. Import Necessary Modules:
import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd
Copy after login

Replace sys.version_info[0] with 3 for Python 3 or 2 for Python 2.

  1. Create a String Buffer:
TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)
Copy after login

Replace the contents of the triple quotes with your test data.

  1. Read String Buffer into DataFrame:
df = pd.read_csv(TESTDATA, sep=";")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template