【问题标题】:How to read csv into multi-dimensional array如何将csv读入多维数组
【发布时间】:2014-05-17 12:32:55
【问题描述】:

我正在尝试读取 CSV,其中前四列是多维数组的索引。我得到错误:

KeyError: 0

来自:

sp = []
csvFile = open("sp.csv", "rb")
csvReader = csv.reader(csvFile)
for row in csvReader:
    print row
    sp[int(row[0])][int(row[1])][int(row[2])][int(row[3])] = float(row[4])

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    你需要在每个维度初始化一个字典,例如sp[int(row[0])]需要先分配,然后才能使用[int(row[1])]访问它

    编辑。根据您的用例,您可能会逃脱

    sp = {}
    sp[(int(row[0]), int(row[1]), ..] = float(row[4])
    

    又一个编辑。我在想你可能会使用numpy 并最终得到这个问题:Python multi-dimensional array initialization without a loop 这实际上反映了你的问题。它包含一个非numpy 解决方案作为接受的答案。不过,您需要知道它的尺寸。

    【讨论】:

    • 叹息,所以 n^4?认为python比那更好:(
    • collections.defaultdict 有帮助,但只有一层深度
    • @Tjorriemorrie:虽然它需要更多内存,但您可以将多维数组设为字典字典,从而避免预先分配其中的每个条目。
    • @martineau 我不好的是我的评论中已经在考虑字典。但是,即使 sp[int(row[0])] 默认为 {},您也需要在 position[int(row[1])] 处将其初始化为新的 {},然后才能分配给它
    • @Nicolas78:可以使用defaultdict 并避免进行所有初始化——它被称为autovivification。看我的回答。
    【解决方案2】:

    您可以使用这样的字典字典来代替数组,以避免必须预先分配整个结构:

    from collections import defaultdict
    tree = lambda: defaultdict(tree)
    
    sp = tree()
    
    print 3 in sp[1][2]  # -> False
    sp[1][2][3] = 4.1
    print 3 in sp[1][2]  # -> True
    print sp[1][2][3]  # -> 4.1
    
    sp[9][7][9] = 5.62
    sp[4][2][0] = 6.29
    

    【讨论】:

    • 这是一件美丽的事情。
    • 我似乎无法让它工作,你能不能详细说明一下?我的sp[1][2][3] 返回defaultdict(<function <lambda> at 0x10cf05230>, {})
    • 这是因为在引用 sp[1][2][3] 的内容之前,您没有为其分配终端(又名“叶子”)值,因此自动创建了一个空的 defaultdict(又名“分支”节点)默认。这不是引发KeyError: 3,因为sp[1][2] 中的defaultdict(也是自动创建的)没有该键的值。
    【解决方案3】:

    使用 Numpy 怎么样? sp.csv 可能如下所示:

    0,0,0,4.1
    1,1,2,5.2
    0,1,1,3.2
    

    然后,使用Numpy,从文件读取变成单行:

    import numpy as np
    sp = np.loadtxt('sp.csv', delimiter=',')
    

    这会产生一个二维记录数组:

    array([[ 0. ,  0. ,  0. ,  4.1],
           [ 1. ,  1. ,  2. ,  5.2],
           [ 0. ,  1. ,  1. ,  3.2]])
    

    假设基于 0 的索引,将此稀疏矩阵转换为完整的 ndarray 的工作方式如下。我对idx= 行不满意(必须有更直接的方法),但它有效:

    max_indices = sp.max(0)[:-1]
    fl = np.zeros(max_indices + 1)
    for row in sp:
        idx = tuple(row[:-1].astype(int))
        fl[idx] = row[-1]
    

    导致以下 ndarray fl:

    array([[[ 4.1,  0. ,  0. ],
            [ 0. ,  3.2,  0. ]],
    
           [[ 0. ,  0. ,  0. ],
            [ 0. ,  0. ,  5.2]]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 2013-09-22
      相关资源
      最近更新 更多