2016-10-07 108 views
1

我有類似的文件中的以下數據:數據提取:創建具有列表字典辭典在python

Name, Age, Sex, School, height, weight, id 

Joe, 10, M, StThomas, 120, 20, 111 

Jim, 9, M, StThomas, 126, 22, 123 

Jack, 8, M, StFrancis, 110, 15, 145 

Abel, 10, F, StFrancis, 128, 23, 166 

的實際數據可能是100列和一百萬行。

我所要做的是創建在以下模式的字典(在計算方面非常昂貴)

school_data = {'StThomas': {'weight':[20,22], 'height': [120,126]}, 
       'StFrancis': {'weight':[15,23], 'height': [110,128]} } 

事情我想:

  1. 試用1

    school_names = [] 
    for lines in read_data[1:]: 
        data = lines.split('\t') 
        school_names.append(data[3]) 
    
    school_names = set(school_names) 
    
    for lines in read_data[1:]: 
        for school in schools: 
         if school in lines: 
          print lines 
    
  2. 試驗2:

    for lines in read_data[1:]: 
        data = lines.split('\t') 
        school_name = data[3] 
        height = data[4] 
        weight = data[5] 
        id = data [6] 
        x[id] = {school_name: (weight, height)} 
    

以上兩種方法是我試圖繼續進行但沒有接近解決方案的方法。

+0

什麼其他列?它們是否與計算有關?或者您是否希望使用這些額外的列與您使用體重/身高(學校的團體價值)所做的相同? – Cadu

回答

1

到標準庫中最簡單的方法是使用現有的工具,csv.DictReadercollections.defaultdict

from collections import defaultdict 
from csv import DictReader 

data = defaultdict(lambda: defaultdict(list)) # * 

with open(datafile) as file_: 
    for row in DictReader(file_): 
     data[row[' School'].strip()]['height'].append(int(row[' height'])) 
     data[row[' School'].strip()]['weight'].append(int(row[' weight'])) 

注意,在例如空間由於輸入文件的標題行中有空格,因此需要使用' School'.strip()。結果:

>>> data 
defaultdict(<function <lambda> at 0x10261c0c8>, {'StFrancis': defaultdict(<type 'list'>, {'weight': [15, 23], 'height': [110, 128]}), 'StThomas': defaultdict(<type 'list'>, {'weight': [20, 22], 'height': [120, 126]})}) 
>>> data['StThomas']['height'] 
[120, 126] 

或者,如果你打算做進一步的分析,看看像​​及其DataFrame數據結構。

* 看到Python defaultdict and lambda,如果這似乎不可思議

+0

很棒!謝謝 –

+0

@LaughingBuddha http://stackoverflow.com/help/someone-answers – jonrsharpe