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

How to Create a Pandas DataFrame from a String?

Linda Hamilton
Release: 2024-11-26 07:21:13
Original
930 people have browsed it

How to Create a Pandas DataFrame from a String?

Pandas Dataframe from a String

To load data from a string into a Pandas Dataframe, you can leverage the io.StringIO class. This approach is particularly useful for testing purposes.

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
"""
Copy after login

To create a Dataframe from this string:

  1. Import io.StringIO:
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO
Copy after login
  1. Create a StringIO object from the data:
TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)
Copy after login
  1. Use Pandas' read_csv function with the StringIO object:
import pandas as pd

df = pd.read_csv(TESTDATA, sep=";")
Copy after login

This code will create a Dataframe named 'df' containing the columns 'col1', 'col2', and 'col3' with the values defined in the string.

The above is the detailed content of How to 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