Skip to content
Related Articles

Related Articles

Construct a DataFrame in Pandas using string data

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 26 Jan, 2019

As we know that data comes in all shapes and sizes. They often come from various different sources having different formats. For an aspiring data scientist, it is very important that they know their way around data i.e. loading and storing data present in various formats.

We have some data present in string format, discuss ways to load that data into pandas dataframe.

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




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

As we can see in the output, we have successfully read the given data in string format into a Pandas DataFrame.
 
Solution 2 : Another fantastic approach is to use the pandas pd.read_clipboard() function.




# 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
    """
  
# Now we copy the data to our clipboard.

Output :

This is what it looks like after we copy the data to clipboard.

Now we will use pandas pd.read_clipboard() function to read the data into a DataFrame




# Read data 
df = pd.read_clipboard(sep = ';')
  
# Print the DataFrame
print(df)

Output :


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!