Construct a DataFrame in Pandas using string data
Last Updated :
11 Jul, 2024
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.
Python
# 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.
Python
# 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
Construct a DataFrame in Pandas using string data – FAQs
How to Make a Pandas DataFrame from a String
If you have string data formatted as a CSV or similarly structured data, you can use Python’s StringIO module to simulate a file-like object, which pandas can then read using read_csv:
import pandas as pd
from io import StringIO
# Example string data formatted as CSV
data = """
A,B,C
1,2,3
4,5,6
7,8,9
"""
# Use StringIO to simulate a file-like object
string_data = StringIO(data)
# Read the string data into a DataFrame
df = pd.read_csv(string_data)
print(df)
How to Convert a String to Data in Pandas
The above method using StringIO is also the approach to convert any well-formatted string that represents tabular data into a DataFrame in pandas.
How to Convert Text to DataFrame in Python
If the text data is structured with separators and consistent rows and columns, you can use the read_csv function by specifying the appropriate separator. Here’s an example with tab-separated values:
data = """
A\tB\tC
1\t2\t3
4\t5\t6
"""
string_data = StringIO(data)
df = pd.read_csv(string_data, sep='\t')
print(df)
How to Read CSV File from String in Pandas
As demonstrated above, the process involves wrapping the string with StringIO and passing it to pd.read_csv(). This method is perfect for reading data received in string format directly into a DataFrame without needing to save it first.
How to Write a String to CSV in Python
To write string data to a CSV file in Python, you typically format the string as CSV and then write it using Python’s file handling functions. However, if you’re working within the pandas framework, you can convert your string to a DataFrame and then use to_csv():
# Assuming df is your DataFrame created from string data
df.to_csv('output.csv', index=False) # 'index=False' to avoid writing row indices
For a pure Python approach without using pandas:
data = "A,B,C\n1,2,3\n4,5,6"
# Write to a CSV file
with open('output.csv', 'w') as file:
file.write(data)