Thursday, January 22, 2026
HomeLanguagesConstruct a DataFrame in Pandas using string data

Construct a DataFrame in Pandas using string data

As we know that data comes in all shapes and sizes. They often come from various sources having different formats. We have some data present in string format, and discuss ways to load that data into Pandas Dataframe.

Method 1: Create Pandas DataFrame from a string using StringIO() 

One way to achieve this is by using the StringIO() function. It will act as a wrapper and it will help us to read the data using the pd.read_csv() function. 

Python3




# importing pandas as pd
import pandas as pd
 
# import the StrinIO function
# from io module
from io import StringIO
 
# wrap the string data in StringIO function
StringData = StringIO("""Date;Event;Cost
    10/2/2011;Music;10000
    11/2/2011;Poetry;12000
    12/2/2011;Theatre;5000
    13/2/2011;Comedy;8000
    """)
 
# let's read the data using the Pandas
# read_csv() function
df = pd.read_csv(StringData, sep =";")
 
# Print the dataframe
print(df)


Output :

            Date    Event   Cost
0 10/2/2011 Music 10000
1 11/2/2011 Poetry 12000
2 12/2/2011 Theatre 5000
3 13/2/2011 Comedy 8000

Method 2: Create Pandas DataFrame from a string using Pandas read_clipboard()

Another fantastic approach is to use the Pandas pd.read_clipboard() function. This is what it looks like after we copy the data to the clipboard. Now we will use Pandas pd.read_clipboard() function to read the data into a DataFrame.

Python3




# importing pandas as pd
import pandas as pd
 
# This is our string data
StringData ="""Date;Event;Cost
    10/2/2011;Music;10000
    11/2/2011;Poetry;12000
    12/2/2011;Theatre;5000
    13/2/2011;Comedy;8000
    """
 
# Read data
df = pd.read_clipboard(sep = ';')
 
# Print the DataFrame
print(df)


Output :

            Date    Event   Cost
0 10/2/2011 Music 10000
1 11/2/2011 Poetry 12000
2 12/2/2011 Theatre 5000
3 13/2/2011 Comedy 8000
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
119 POSTS0 COMMENTS
Nango Kala
6847 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12064 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7220 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6912 POSTS0 COMMENTS