【问题标题】:How to reduce matrix cols in python?如何减少python中的矩阵列?
【发布时间】:2013-11-28 09:49:47
【问题描述】:

我有一个包含大量数据、22 列和 10000 行的 csv 文件。 第一行是标题,所有其他行是数据。 我从文件中读取。 (只是阅读,我不想更改原始文件) 现在我想通过标题名称减少列数并仅保存 3 列并保存它。 cols 的顺序可以在文件之间更改,有时“LUX” col 将在 col 编号 5 中,有时在 col 编号 20 或 8 中,等等。 到目前为止,我得到了这个:

with open('test.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file

medianGoodPixels = [] #vector to pixels
Lux = [] #vector to LUX
sdVer = [] # vector to the version
NewCsvTable = [] #will be a matrix with 3 cols, LUX, pixels, and version

for row in spamreader:
    if row == "LUX": 
         #Here I'm stuck

我意识到像这样的行,将在每次迭代中给出所有行,所以在第二次迭代中,它只是第二行的数据。 我想我需要以某种方式使用 2 个循环,但不知道具体如何。

谢谢。

【问题讨论】:

    标签: python loops csv matrix


    【解决方案1】:

    您可以在标题行使用list.index来查找各种标题的索引。

    with open('test.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file
        medianGoodPixels = [] #vector to pixels
        Lux = [] #vector to LUX
        sdVer = [] # vector to the version
        NewCsvTable = [] #will be a matrix with 3 cols, LUX, pixels, and version
        header = next(spamreader)  #Returns the header 
        lux_col, pixel_col, version_col = header.index('LUX'), header.index('pixel'),\
                                          header.index('version')
    
        #Now iterate over rest of the rows. 
        for row in spamreader:
            Lux.append(row[lux_col])
            sdVer.append(row[version_col])
            medianGoodPixels.append(row[pixel_col])  
    

    【讨论】:

      【解决方案2】:

      这绝对是专门的 csv 模块类 csv.DictReader 的工作,它使用文档的第一行来找出列名是什么,然后每行返回一个字典。

      例子:

      Lux, sdVer, medianGoodPixels = [], [], []
      with open('test.csv', 'rb') as csvfile:
          csv_reader = csv.DictReader(csvfile, delimiter=',', quotechar='|')
          for dict_row in csv_reader:
              Lux.append(dict_row['LUX'])
              sdVer.append(dict_row['version'])
              medianGoodPixel.append(dict_row['pixel'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-04
        • 1970-01-01
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 2018-03-07
        相关资源
        最近更新 更多