2016-08-29 2 views
1

используя numpy genfromtxt в python, я хочу иметь возможность получить заголовки столбцов в качестве ключа для данных. Я попробовал следующее, но не смог получить имена столбцов для соответствующих данных.получить имена столбцов из numpy genfromtxt в python

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" 
    } 
} 

какие-либо предложения?

+2

Вы рассмотрели [панды] (http://pandas.pydata.org/)? – bananafish

ответ

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']} 
+0

Это отлично работало с numpy. Большое спасибо. Я не могу использовать панды, поскольку новые установки в моем случае очень селективны, если это не оправдано. – user2406718

2

Использование панды модуля:

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 

получение желаемого Dict:

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}}' 
+0

Почему 3,3999999999999999 ?? – RAVI

+0

@RAVI, это представление python/pandas '4.0';) – MaxU

+0

Почему только 3.4 -> 3.3999999999999999, а не любые другие значения, такие как 2.0 -> 1.9999999999999999 ?? Также на выходе to_json он получил 3.4 правильно. Есть ли проблема в to_dict ?? – RAVI