Parsing an irregularly spaced text file in Python pandas
<p>I have a text file that looks like :</p>

<pre><code>Date     Fruit-type  Color         count
aug-6     apple  green         4
aug-7     pear  brown         5
aug-3     peach  yellow         10
aug-29     orange  orange         34
</code></pre>

<p>I would like to parse it to remove the irregular spaces into a nicely formatted pandas dataframe. I thought to remove the spaces and replace them with another delimiter but could not figure out the logic.</p>

<p>Desired output</p>

<pre><code>Date,Fruit-type,Color,count
aug-6,apple,green,4
aug-7,pear,brown,5
aug-3,peach,yellow,10
aug-29,orange,orange,34
</code></pre>

<p>If you can use command line tools, you can run this <code>awk</code> command to turn it from space delimited to comma delimited.</p>

<pre><code>awk '{for (i=1; i&lt;NF; i++){printf "%s,", $i} print $NF}' data.txt
</code></pre>

<p>Otherwise, pandas can import space delimited files easily.</p>

<pre><code>import pandas as pd

frame = pd.read_table('data.txt', sep='\s+')
</code></pre>

<p>With data.txt as:</p>

<pre><code>Date     Fruit-type  Color         count
aug-6     apple  green         4
aug-7     pear  brown         5
aug-3     peach  yellow         10
aug-29     orange  orange         34
</code></pre>

<p>The output is </p>

<pre><code>     Date Fruit-type   Color  count
0   aug-6      apple   green      4
1   aug-7       pear   brown      5
2   aug-3      peach  yellow     10
3  aug-29     orange  orange     34
</code></pre>

<p>You can read more here: <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#csv-text-files">http://pandas.pydata.org/pandas-docs/stable/io.html#csv-text-files</a></p>

python pandas