Construct a DataFrame in Pandas using string data

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.