【问题标题】:Create dictionary, only adding rows where one column matches a value in a list创建字典,仅添加一列与列表中的值匹配的行
【发布时间】:2014-02-15 17:39:36
【问题描述】:

我有 2 个 CSV 文件。

首先,我想取 1 列并列一个列表。

然后我想从另一个 CSV 创建一个字典,但只包含一个列中的值与之前创建的列表中的值匹配的行。

这是目前为止的代码:

#modified from: http://bit.ly/1iOS7Gu
import pandas
colnames = ['Gene > DB identifier', 'Gene_Symbol',  'Gene > Organism > Name', 'Gene > Homologues > Homologue > DB identifier',  'Homo_Symbol',  'Gene > Homologues > Homologue > Organism > Name',  'Gene > Homologues > Data', 'Sets > Name']
data = pandas.read_csv(raw_input("Enter csv file (including path)"), names=colnames)

filter = set(data.Homo_Symbol.values)

print set(data.Homo_Symbol.values)

#new_dict = raw_input("Enter Dictionary Name")
#source: http://bit.ly/1iOS0e3
import csv
new_dict = {}
with open('C:\Users\Chris\Desktop\gwascatalog.csv', 'rb') as f:
  reader = csv.reader(f)
  for row in reader:
      if row[0] in filter:
        if row[0] in new_dict:
            new_dict[row[0]].append(row[1:])
        else:
            new_dict[row[0]] = [row[1:]]
print new_dict

这是 2 个示例数据文件:http://bit.ly/1hlpyTH

有什么想法吗?提前致谢。

【问题讨论】:

    标签: python list dictionary genetics


    【解决方案1】:

    您可以使用collections.defaultdict 摆脱对字典中的列表的检查:

    from collections import defaultdict
    
    new_dict = defaultdict(list)
    #...
       for row in reader:
          if row[0] in filter:
             new_dict[row[0]].append(row[1:])
    

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 2010-12-01
      • 1970-01-01
      相关资源
      最近更新 更多