get column names from numpy genfromtxt in python
<p>using numpy genfromtxt in python, i want to be able to get column headers as key for a given data.  I tried the following, but not able to get the column names for the corresponding data.</p>

<pre><code>column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0))
columnData = np.genfromtxt(pathToFile,dtype=str,delimiter=',')
data = dict(zip(column,columnData.tolist()))
</code></pre>

<p>Below is the data file</p>

<pre><code>header0,header1,header2
mydate,3.4,2.0
nextdate,4,6
afterthat,7,8
</code></pre>

<p>Currently, it shows data as </p>

<pre><code>{
  "mydate": [
    "mydate",
    "3.4",
    "2.0"
  ],
  "nextdate": [
    "nextdate",
    "4",
    "6"
  ],
  "afterthat": [
    "afterthat",
    "7",
    "8"
  ]
}
</code></pre>

<p>I want to get to this format</p>

<pre><code>{
  "mydate": {
    "header1":"3.4",
    "header2":"2.0"
  },
  "nextdate": {
    "header1":"4",
    "header2":"6"
  },
  "afterthat": {
   "header1":"7",
   "header2":  "8"
  }
}
</code></pre>

<p>any suggestions?</p>

<p>Using pandas module:</p>

<pre><code>In [94]: fn = r'D:\temp\.data\z.csv'
</code></pre>

<p>read CSV into data frame:</p>

<pre><code>In [95]: df = pd.read_csv(fn)

In [96]: df
Out[96]:
     header0  header1  header2
0     mydate      3.4      2.0
1   nextdate      4.0      6.0
2  afterthat      7.0      8.0
</code></pre>

<p>getting desired dict:</p>

<pre><code>In [97]: df.set_index('header0').to_dict('index')
Out[97]:
{'afterthat': {'header1': 7.0, 'header2': 8.0},
 'mydate': {'header1': 3.3999999999999999, 'header2': 2.0},
 'nextdate': {'header1': 4.0, 'header2': 6.0}}
</code></pre>

<p>or as a JSON string:</p>

<pre><code>In [107]: df.set_index('header0').to_json(orient='index')
Out[107]: '{"mydate":{"header1":3.4,"header2":2.0},"nextdate":{"header1":4.0,"header2":6.0},"afterthat":{"header1":7.0,"header2":8.0}}'
</code></pre>

python numpy genfromtxt