This answer applies when a string is manually entered, not when it's read from somewhere.
A traditional variable-width CSV is unreadable for storing data as a string variable. Especially for use inside a .py
file, consider fixed-width pipe-separated data instead. Various IDEs and editors may have a plugin to format pipe-separated text into a neat table.
Store the following in a utility module, e.g. util/pandas.py
. An example is included in the function's docstring.
import io
import re
import pandas as pd
def read_psv(str_input: str, **kwargs) -> pd.DataFrame:
"""Read a Pandas object from a pipe-separated table contained within a string.
Input 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.
Ref: https://stackoverflow.com/a/46471952/
"""
substitutions = [
('^ *', ''), # Remove leading spaces
(' *$', ''), # Remove trailing spaces
(r' *\| *', '|'), # Remove spaces between columns
]
if all(line.lstrip().startswith('|') and line.rstrip().endswith('|') for line in str_input.strip().split('\n')):
substitutions.extend([
(r'^\|', ''), # Remove redundant leading delimiter
(r'\|$', ''), # Remove redundant trailing delimiter
])
for pattern, replacement in substitutions:
str_input = re.sub(pattern, replacement, str_input, flags=re.MULTILINE)
return pd.read_csv(io.StringIO(str_input), sep='|', **kwargs)
Non-working alternatives
The code below doesn't work properly because it adds an empty column on both the left and right sides.
df = pd.read_csv(io.StringIO(df_str), sep=r'\s*\|\s*', engine='python')
As for read_fwf
, it doesn't actually use so many of the optional kwargs that read_csv
accepts and uses. As such, it shouldn't be used at all for pipe-separated data.
pd.read_table()
is an equivalent function, just slightly better nomenclature:df = pd.read_table(TESTDATA, sep=";")
. – Infiltration