pandas read_csv with pound sign in column headers
<p>I need to read data from a tab-delimited file where the 1st row contains column headers but the 1st character of that row is a pound sign/octothorpe/hastag <code>#</code>.</p>

<p>The data look like this:</p>

<pre><code>FILE_CONTENTS = """\
#   year-month-day  spam    eggs
1956-01-31  11  21
1985-03-20  12  22
1940-11-22  13  23
"""
</code></pre>

<p>I have a solution (answer posted below) but it feels like there is probably a better way.</p>

<p>There is a <a href="http://stackoverflow.com/questions/7086945%20%22related%20question%20about%20doing%20this%20in%20R2">related question about doing this in R</a>.</p>

<p>This gives the desired <code>DataFrame</code></p>

<pre><code>from io import StringIO
import pandas as  pd

FILE_CONTENTS = """\
# year-month-day    spam    eggs
1956-01-31  11  21
1985-03-20  12  22
1940-11-22  13  23
"""
df = pd.read_csv(StringIO(FILE_CONTENTS), delim_whitespace=True, escapechar='#')
df.columns = df.columns.str.strip()
</code></pre>

<p>N.B. edited to include <a href="http://stackoverflow.com/users/704848/edchum">EdChum</a>'s fix for the leading white-space in initial column, supplied in <a href="http://stackoverflow.com/questions/39485976/pandas-read-csv-with-pound-sign-in-column-headers#comment66290633_39485977">comment</a>.</p>

<p>And seems preferable to various kludges I tried along the lines of:</p>

<pre><code>with open(filename) as f:
    header = f.readline()
cols = header.strip('#').split()
df = pd.read_csv(..., comment='#', names=cols)
</code></pre>

<p>edit: seeing <a href="http://stackoverflow.com/users/6207849/nickil-maveli">Nickil Maveli</a>'s answer i realize that I have to deal with both <code>#&lt;space&gt;year-month-day ...</code> <em>and</em>  <code>#&lt;tab&gt;year-month-day ...</code> in the file headers.
So we will need a combination of Nikil's and EdChum's approaches</p>

python python-3.x pandas