Q:

Create Pandas DataFrame from a string

belongs to collection: Python Pandas Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Pandas Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to add an empty column to a DataFrame?... >>
<< Convert DataFrame column type from string to datet...