A traditional variable-width CSV cannot be read to store data as a string variable. Specifically for use inside a .py file, instead consider pipe-wise data of a fixed width. Various IDEs and editors may have a plugin for formatting pipe-split text into a neat table.
The following works for me. To use it, save it to a file, for example, pandas_util.py . An example is included in the docstring function. If you are using a version of Python older than 3.6, remove the type annotations from the function definition line.
import re import pandas as pd def read_pipe_separated_str(str_input: str, **kwargs) -> pd.DataFrame: """Read a Pandas object from a pipe-separated table contained within a string. Example: | int_score | ext_score | eligible | | | 701 | True | | 221.3 | 0 | False | | | 576 | True | | 300 | 600 | True | The leading and trailing pipes are optional, but if one is present, so must be the other. 'kwargs' are passed to 'read_csv'. They must not include 'sep'. In PyCharm, the "Pipe Table Formatter" plugin has a "Format" feature that can be used to neatly format a table. """
Broken Alternative:
The code below does not work properly, because it adds an empty column on the left and right sides.
df = pd.read_csv(pd.compat.StringIO(df_str), sep=r'\s*\|\s*', engine='python')
ABB Sep 28 '17 at 14:42 on 2017-09-28 14:42
source share