【问题标题】:Transposing the data from csv file to csv using python or Matlab使用 python 或 Matlab 将数据从 csv 文件转换为 csv
【发布时间】:2016-05-11 17:10:08
【问题描述】:

我正在处理具有四列和 912500 行的 csv 格式的数据。我需要将每列中的数据转换为单独的 csv 文件中的 365 列和 2500 行。例如。

Col1 Col2 Col3 Col4

1 33 36 38

2 25 18 56

365 -4 -3 10

366 -11 20 35

367 12 18 27 . .

730 26 36 27 . .

。 912500 20 37 42

期望的输出

Col1  Col2 Col3  Col4 Col5 .....Col 365 

1 33 25.................................-4

2 -11 12 .................... 26

3

4.......

5………… . .

2500.................................

请告诉我如何为此编写脚本?任何帮助将不胜感激。

【问题讨论】:

  • 这个问题真的很令人困惑,我认为你需要更好地格式化和完善你所问的内容。您希望每 91~92 (365/4) 行合并成一个 365 列的行吗?
  • 他想获取原始数据的 X 列(912500 行),然后将其重新格式化为大小为 2500*365 的矩阵(=912500 个条目)。 @Sam:一列原始数据A可以这样选择:A(:,1),那么你需要使用reshape() -> de.mathworks.com/help/matlab/ref/reshape.html 很简单。
  • 您可以使用 Numpy 在 Python 中进行重塑。
  • 感谢大家的回复。我能够重塑所需矩阵中的数据。感谢您的帮助和支持。

标签: python matlab csv


【解决方案1】:

尝试按照 cmets 中的建议使用 NumPy,但是,如果您想自己编写代码,可以采用以下一种方法:

  • 您可以一次读取一行文件

  • 使用逗号作为分隔符分割每一行

  • 丢弃“行数”(拆分操作后得到的列表的第一个元素)。您必须保持自己的行数。

  • 将剩余元素复制到另一个列表,直到有 365 个元素(包括行数)
  • 将此列表以 CSV 格式写入输出文件。您可以使用 Python 的内置 CSV 写入器 (https://docs.python.org/2/library/csv.html)
  • 重复直到处理完整个输入文件。

【讨论】:

    【解决方案2】:

    csv.reader 将创建一个逐行读取 csv 的迭代器。然后,您可以将其输入itertools.chain,它依次迭代每一行,输出各个列。现在您有了一个列流,您可以将它们分组为所需大小的新行。有几种方法可以重建这些行,我在示例中使用了 itertools.groupby

    import itertools
    import csv
    
    def groupby_count(iterable, count):
        counter = itertools.count()
        for _, grp in itertools.groupby(iterable, lambda _: next(counter)//count):
            yield tuple(grp)
    
    def reshape_csv(in_filename, out_filename, colsize):
        with open(in_filename) as infile, open(out_filename, 'w') as outfile:
            reader = csv.reader(infile, delimiter=' ')
            writer = csv.writer(outfile, delimiter=' ')
            col_iter = itertools.chain.from_iterable(reader)
            writer.writerows(groupby_count(col_iter, colsize))
    

    这里有一个示例脚本进行测试。不过,我使用了更少的列:

    import os
    infn = "intest.csv"
    outfn = "outtest.csv"
    orig_colsize = 4
    new_colsize = 15
    
    # test input file
    with open(infn, "w") as infp:
        for i in range(32):
            infp.write(' '.join('c{0:02d}_{1:02d}'.format(i,j) for j in range(4)) + '\n')
    
    # remove stale output file
    try:
        os.remove(outfn)
    except OSError:
        pass
    
    # run it and print
    reshape_csv(infn, outfn, new_colsize)
    print('------- test output ----------')
    print(open(outfn).read())
    

    【讨论】:

      【解决方案3】:

      以下内容针对伪造的数据文件进行了测试,对我来说效果很好,但是 ymmv... 请参阅内联 cmets 了解工作原理

      import csv
      
      # we open the data file and put its content in data, that is a list of lists
      with open('data.csv') as csvfile:
          data = [row for row in csv.reader(csvfile)]
      
      # the following idiom transpose a list of lists
      transpose = zip(*data)
      
      # I use Python 3, hence zip is a generator and I have to throw away using next()
      # the first element, i.e., the column of the row numbers
      next(transpose)
      
      # I enumerate transpose, obtaininig the data column by column    
      for nc, column in enumerate(transpose):
      
          # I prepare for writing to a csv file
          with open('trans%d.csv'%nc, 'w') as outfile:
              writer = csv.writer(outfile)
      
              # here, we have an idiom, sort of..., please see
              #   http://stupidpythonideas.blogspot.it/2013/08/how-grouper-works.html
              # for the reason why what we enumerate are the rows of your output file
              for nr, row in enumerate(zip(*[iter(column)]*365)):
                  writer.writerow([nr+1,*row])
      

      【讨论】:

        猜你喜欢
        • 2016-02-18
        • 1970-01-01
        • 2019-04-13
        • 2017-11-05
        • 1970-01-01
        • 2015-04-12
        • 1970-01-01
        • 1970-01-01
        • 2020-11-11
        相关资源
        最近更新 更多