gpt4 book ai didi

python - 数据提取: Creating dictionary of dictionaries with lists in python

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:08 26 4
gpt4 key购买 nike

我的文件中有类似于以下内容的数据:

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 列和 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)}

以上两种方法是我尝试继续进行但没有更接近解决方案的方法。

最佳答案

在标准库中执行此操作的最简单方法是使用现有工具,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]

或者,如果您打算进行进一步分析,请查看类似 pandas 的内容。及其 DataFrame 数据结构。

* 参见Python defaultdict and lambda如果这看起来很奇怪

关于python - 数据提取: Creating dictionary of dictionaries with lists in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39918972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com