在python中使用numpy genfromtxt,我希望能够将列标题作为给定数据的关键。我尝试了以下操作,但无法获取相应数据的列名。
column = np.genfromtxt(pathToFile,dtype=str,delimiter=',',usecols=(0))
columnData = np.genfromtxt(pathToFile,dtype=str,delimiter=',')
data = dict(zip(column,columnData.tolist()))
以下是数据文件
header0,header1,header2
mydate,3.4,2.0
nextdate,4,6
afterthat,7,8
目前,它将数据显示为
{
"mydate": [
"mydate",
"3.4",
"2.0"
],
"nextdate": [
"nextdate",
"4",
"6"
],
"afterthat": [
"afterthat",
"7",
"8"
]
}
我想采用这种格式
{
"mydate": {
"header1":"3.4",
"header2":"2.0"
},
"nextdate": {
"header1":"4",
"header2":"6"
},
"afterthat": {
"header1":"7",
"header2": "8"
}
}
有什么建议吗?
答案 0 :(得分:2)
使用pandas模块:
In [94]: fn = r'D:\temp\.data\z.csv'
将CSV读入数据框:
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
得到理想的词典:
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}}
或作为JSON字符串:
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}}'
答案 1 :(得分:1)
使用您的示例文件和genfromtxt
调用,我得到2个数组:
In [89]: column
Out[89]:
array(['header0', 'mydate', 'nextdate', 'afterthat'],
dtype='<U9')
In [90]: columnData
Out[90]:
array([['header0', 'header1', 'header2'],
['mydate', '3.4', '2.0'],
['nextdate', '4', '6'],
['afterthat', '7', '8']],
dtype='<U9')
拉出columnData
In [91]: headers=columnData[0,:]
In [92]: headers
Out[92]:
array(['header0', 'header1', 'header2'],
dtype='<U9')
现在构建一个字典词典(我不需要单独的column
数组):
In [94]: {row[0]: {h:v for h,v in zip(headers, row)} for row in columnData[1:]}
Out[94]:
{'afterthat': {'header0': 'afterthat', 'header1': '7', 'header2': '8'},
'mydate': {'header0': 'mydate', 'header1': '3.4', 'header2': '2.0'},
'nextdate': {'header0': 'nextdate', 'header1': '4', 'header2': '6'}}
稍微改进一下:
In [95]: {row[0]: {h:v for h,v in zip(headers[1:], row[1:])} for row in columnData[1:]}
Out[95]:
{'afterthat': {'header1': '7', 'header2': '8'},
'mydate': {'header1': '3.4', 'header2': '2.0'},
'nextdate': {'header1': '4', 'header2': '6'}}
我喜欢词典理解!
您的列表字典版本:
In [100]: {row[0]:row[1:] for row in columnData[1:].tolist()}
Out[100]: {'afterthat': ['7', '8'], 'mydate': ['3.4', '2.0'], 'nextdate': ['4', '6']}