【问题标题】:add column to csv when exporting numpy ndarray导出 numpy ndarray 时将列添加到 csv
【发布时间】:2015-08-17 08:01:47
【问题描述】:

我正在尝试将 2d numpy 数组导出到 csv,同时插入一个由数组外部的变量组成的额外列。

最终目标是使用 python lasio 库遍历一系列文件,选择某些 1d 数组,将它们展平为 2d 数组,然后导出为准备将数据加载到数据库的 csv 文件。

ndarrays 可能是:

文件 1:

1.0, 3
1.5, 4
2.0, 56

文件 2:

1.0, 76
1.5, 3
2.0, 45
2.5, 45.6

期望的输出是:

F1, 1.0, 3
F1, 1.5, 4
F1, 2.0, 56
F2, 1.0, 76
F2, 1.5, 3
F2, 2.0, 45
F2, 2.5, 45.6

【问题讨论】:

    标签: python arrays csv numpy


    【解决方案1】:

    这可以用numpy来完成,如下,

    import numpy as np
    
    #Read and label file 1
    f1 = np.genfromtxt('./file1.csv',delimiter=',',dtype="string")
    label = np.array(["F1"]*f1.shape[0])
    f1 = np.insert(f1, 0, label, axis=1)
    
    
    #Read and label file 2
    f2 = np.genfromtxt('./file2.csv',delimiter=',',dtype="string")
    label = np.array(["F2"]*f2.shape[0])
    f2 = np.insert(f2, 0, label, axis=1)
    
    #Combine and write
    fout = np.vstack((f1,f2))
    np.savetxt("fout.csv", fout, delimiter=",", fmt="%s")
    

    Numpy insert 在组合数组时需要相同格式的所有数据。 file1.csvfile2.csv 文件包含您问题中的数组,因此应作为字符串读取。标签是根据列数生成的,并作为第一列插入。然后将两者垂直堆叠并写出。您需要向savetext 指定输出也是一个字符串。然后生成的文件fout.csv 是,

    F1,1.0, 3
    F1,1.5, 4
    F1,2.0, 56
    F2,1.0, 76
    F2,1.5, 3
    F2,2.0, 45
    F2,2.5, 45.6
    

    【讨论】:

      【解决方案2】:

      如果我正确理解您的问题,您可以在每个文件中添加一个 id 列,然后连接所有数组。下面是只有两个数组的代码:

      import numpy as np
      
      A1 = np.array([[1.0, 3],
                     [1.5, 4],
                     [2.0, 56]])
      A2 = np.array([[1.0, 76],
                     [1.5, 3],
                     [2.0, 45],
                     [2.5, 45.6]])
      
      A1id = 0
      A2id = 1
      A1 = np.hstack((A1id*np.ones((A1.shape[0], 1)), A1))
      A2 = np.hstack((A2id*np.ones((A2.shape[0], 1)), A2))
      
      result = np.vstack((A1, A2))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 2014-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多