ADVERTISEMENT
ADVERTISEMENT

Create Pandas DataFrame from a string

Given a string, we have to create Pandas DataFrame from the given string.
Submitted by Pranit Sharma, on April 26, 2022

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.

To create a DataFrame with strings, we need to import io module. Inside io module, StringIO method is used to wrap a string and re-writes it in the form of a CSV file which can be further access with the help of pd.read_csv() method.

To work with Python Pandas, we need to import the pandas library. Below is the syntax,

import pandas as pd

Let us understand with the help of an example.

# 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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.