2016-10-07 73 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