Construct DataFrame in Pandas using string data



We have some data in string format, we will discuss how to load this data into pandas dataframe.

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

# import pandas as pd

import pandas as pd

  
# import the StrinIO function
# from the io module

from io import StringIO

  
# wrap string data in a StringIO function

StringData = StringIO ( "" & quot; Date; Event; Cost

  10/2/2011; Music; 10000

11/2/2011; Poetry; 12000

12/2/2011, theater; 5000

2/13/2011, Comedy, 8000

"" " )

 
# let`s read the data with pandas
# read_csv () function

df = pd .read_csv (StringData, sep = ";" )

 
# Print the data frame

print (df)

Output:

Like us we see the output, we have successfully read and the data as a string in a Pandas DataFrame.

Solution 2. Another fantastic approach — use pd.read_clipboard () pandas pd.read_clipboard () .

# import pandas as pd

import pandas as pd

 
# This is our string data

StringData = “” & quot; Date; Event; Cost

10/2/2011; Music; 10000

11/2/2011; Poetry; 12000

12/2/2011, theater; 5000

2/13/2011, Comedy, 8000

"" "

  
# Now we copy the data to our clipboard.

Output:

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

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

# Reading data

df = pd.read_clipboard (sep = `;` )

 
# Print DataFrame

print (df)

Output: