In order to test some functionality I would like to create a DataFrame
from a string. Let's say my test data looks like:
TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""
What is the simplest way to read that data into a Pandas DataFrame
?
A simple way to do this is to use
StringIO
and pass that to thepandas.read_csv
function. E.g:A traditional variable-width CSV is unreadable for storing data as a string variable. Consider fixed-width pipe-separated data instead. Various IDEs and editors may have a plugin to format pipe-separated text into a neat table.
The following works for me. To use it, store it into a file, e.g.
pandas_util.py
. An example is included in the function's docstring. If you're using a version of Python older than 3.6, delete the type annotations from the function definition line.Non-working alternative:
The code below doesn't work properly because it adds an empty column on both the left and right sides.
A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.
Select the content of the string with your mouse:
In the Python shell use
read_clipboard()
Use the appropriate separator: