Create Pandas DataFrame from a String

DataFrame from a String: In this tutorial, we will learn how can we create a Pandas DataFrame from a given string in Python? By Pranit Sharma Last updated : April 19, 2023

What is a DataFrame?

Pandas is a special tool which allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structure in pandas. DataFrames consists of rows, columns and the data. The Data inside the DataFrame can be of any type. Usually, DataFrames are created with the help of dictionaries but here, we are going to learn how to make a DataFrame with strings.

How to Create DataFrame from a String?

To create a DataFrame from a string, you need to import the StringIO module from the io module which is used to wrap a string, then call the read_csv() method to separate the string from the specified delimiter, and assign the resust to the df (DataFrame).

Let us understand with the help of an example.

Python Program to Create Pandas DataFrame from a String

In the following example, we have a string with multiple values separated by semicolon (;). We're creating a DataFrame from these string values.

# Importing pandas package
import pandas as pd

# Importing StringIO module from io module
from io import StringIO

# Creating a string
string= StringIO("""
Name;Age;Gender
Harry;20;Male
Tom;23;Male
Alexa;21;Female
Nancy;20;Female
Jason;25;Male
""")

# Reading String in form of csv file
df=pd.read_csv(string, sep=";")

# Printing the DataFrame
print("String into DataFrame:\n",df)

Output

Output | Create Pandas DataFrame from a String

Python Pandas Programs »

All Python Pandas Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.