Change language

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:

Construct DataFrame in Pandas using string data Python functions: Questions

Construct DataFrame in Pandas using string data sin: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method