【问题标题】:List CSV cells with same value in R or Python?在 R 或 Python 中列出具有相同值的 CSV 单元格?
【发布时间】:2012-12-10 19:09:34
【问题描述】:

我有一个包含机构名称和地址的 CSV。如果我想要一串具有相同地址(特别是相同的邮政编码)的机构名称,我该如何在 R 或 Python 中做到这一点?无论哪种方式最有效都是可取的,但我仍在学习这两种方式。 Google Refine 已经给了我每个邮政编码集群的数量,但我只需要知道哪些机构对应于这些邮政编码。

PS。是的,我知道邮政编码不好依赖;这样做的目的是为了说明这一点。

输入数据示例:

最终输出(稍后与 shapefile 合并):

【问题讨论】:

    标签: python r excel


    【解决方案1】:

    你应该能够构造一个字典:

    import csv
    
    from collections import defaultdict
    
    agencies = defaultdict(list)
    
    with open('file.csv', 'r') as handle:
        reader = csv.reader(handle)
    
        for row in reader:
            agencies[row[2]].append(row[0])
    

    现在,agencies 包含邮政编码到代理商的映射。

    【讨论】:

    • @grich:这是csv 的问题。我以前从未见过它,所以这里有一个 ton of Google results 来解决这个确切的问题。
    • 将列表写入单个单元格怎么样? writerows 只是想将列表中的每个项目分成单独的单元格。
    • @grich:你可以做for zipcode in agencies: writer.writerow(zipcode, *agencies[zipcode])
    【解决方案2】:

    这是使用模拟数据的 R 解决方案的粗略草图:

    set.seed(123)
    dat <- data.frame(agency = sample(letters[1:15],100,replace = TRUE),
                      zipcode = sample(15,100,replace = TRUE))
    
    head(dat)
    
    #A base R solution
    aggregate(dat$agency,
              by = list(dat$zipcode),
              FUN = function(x){paste(x,collapse = ",")})
    
    #Or using the populat plyr package
    library(plyr)
    ddply(dat,
          .(zipcode),
          summarise,
          agencies = paste(agency,collapse = ","))
    

    您的数据的屏幕截图通常不是最有用的展示方式。一个完整的、最小的可重复示例将允许更完整的答案,这些答案更直接有用。 (并减少您提出的后续问题。)

    【讨论】:

    • @grich joran 关于最小可重现示例的评论非常重要。它极大地增加了给出解决实际问题的完整答案的机会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多