【问题标题】:Python Select Specific Row and ColumnPython选择特定的行和列
【发布时间】:2014-08-04 02:22:59
【问题描述】:

我希望从 python 中的 CSV 文件中选择特定的行和列。如果值为空,我想执行一个操作,如果值不为空,我想执行另一个操作。

我认为代码应该是这样的:

inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for row in reader:
    if row[5][6] == '':              ==>  (I mean select value the 5th row and 6th column)
        (do this)
    else:
        (do that)

关于这个主题的任何帮助或指导都会有所帮助——我已经使用列表完成了类似的任务;但是,由于 CSV 文件是原始文件,我不知道该怎么做。

【问题讨论】:

  • 您的意思是您的操作是操作该行的一个字段?

标签: python csv import-from-csv


【解决方案1】:

当您想到 CSV 时,就想到 pandas。

import pandas as pd

df = pd.read_csv('path/to/csv')

if df.iloc[5, 6]:
    # do stuff
else
    # do some other stuff

【讨论】:

  • Pandas 可与许多其他文件分隔符一起使用:csv,或制表符分隔,或任何其他分隔符,甚至是正则表达式。
【解决方案2】:

inspectorG4dget 和 Oscar Lopez 的想法都是正确的,但他们的解决方案存在缺陷。因此,我提出了我自己的。

一般的想法是csv.reader 只是一个特殊的文件对象,它会自动以逗号分隔事物。像对待任何其他文件对象一样对待它。如果你想要第 n 行,迭代直到你到达第 n 行。

with open('inputFile', rb) as f:
  reader = csv.reader(f)
  for i, l in enumerate(reader):
    if i==5:
      try:
        print l[6]
      except IndexError:
        print "Nothing here!"

几点说明:

  • 我使用with 块,以便在完成此代码时安全关闭文件。您随时可以自己拨打file.close,但这是更好的做法。
  • 我将对该行第 6 列的访问封装在 try...except 中,因为可能没有第 6 列。安全总比后悔好。

【讨论】:

    【解决方案3】:

    试试这个:

    inputFile = 'example.csv'
    reader = csv.reader(inputFile, 'rb')
    
    for i, row in enumerate(reader):
        if i == 5:      # here's the row 5
            data = row.split(',')
            if data[6]: # here's the column 6
                pass    # if the position [5][6] is non-empty do something
            else:       # otherwise
                pass    # do something else
    

    【讨论】:

      【解决方案4】:

      您遇到的问题是,您正在查看 csv 文件每一行中第 5 列值的索引 6 处的字符。相反,您要做的是查看文件的第 6 行和该行的第 5 列

      import csv
      def getCell(infilepath, row, col):
          with open(infilepath) as infile:
              reader = csv.reader(infile)
              try:
                  for i in range(row-1):
                      next(reader)
              except:
                  print(infilepath, "does not have ", row, " rows of data")
                  return
              try:
                  line = next(infilepath)
              except:
                  print(infilepath, "does not have ", row, " rows of data")
                  return
              col -= 1
              if len(line) < col:
                  print(infilepath, "does not have ", col, " columns of data on row ", row)
                  return
              return line[col]
      

      现在我们有了获取所需单元格中数据的方法,我们可以继续:

      value = getCell('example.csv', 5, 6)
      if value is not None:  # the value actually exists
          if value == '':
              # do this
          else:
              # do that
      

      【讨论】:

        【解决方案5】:

        我的名字.csv 文件。

        number;first_name;last_name
        1;Baked;Beans
        2;Lovely;Spam  
        3;Wonderful;Spam
        4;Up;Spam
        5;Baked;Beans
        6;Lovely;Spam
        7;Wonderful;Spam
        8;Down;Spam
        9;Baked;Beans
        

        我在 python 中的代码

        import csv
        L = [0, 5, 7]
        
        with open('names.csv',"r") as f:
            r = csv.DictReader(f, delimiter =";")
            for i, line in enumerate(r):
                if i in L:    # or (i+2) in L: from your second example
                    print (line)
                    print (line['first_name'], line['last_name'])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-06
          • 2018-09-10
          • 2012-10-06
          • 1970-01-01
          • 2012-01-02
          • 2022-12-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多