Python选择特定的行和列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25110987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:45:06  来源:igfitidea点击:

Python Select Specific Row and Column

pythoncsvimport-from-csv

提问by Code4Days

I wish to select a specific row and column from a CSV file in python. If the value is blank, I want to perform one action, and if the value is not blank, I want to perform another action.

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

I think the code should look something like this:

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

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)

Any help or guidance on this topic would be helpful -- I've done a similar task using lists; however, since the CSV file is raw, I don't know what to do.

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

采纳答案by bananafish

When you think CSV, think pandas.

当你想到 CSV 时,想想熊猫。

import pandas as pd

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

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

回答by inspectorG4dget

The problem that you are running into, is that you are looking at the character at index 6, of the value at column 5, in every row of the csv file. Instead, what you want to do is look at the 6th row of the file, and the 5th column of that row

您遇到的问题是,您正在查看 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]

Now that we have a way to get the data in the required cell, we can continue:

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

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

回答by óscar López

Try this:

尝试这个:

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

回答by whereswalden

Both inspectorG4dget and Oscar Lopez have the right idea, but there are flaws in their solutions. Thus, I present my own.

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

The general idea is that csv.readeris just a special file object that automatically splits things on commas. Treat it like any other file object. If you want the nth line, iterate until you hit the nth line.

一般的想法是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!"

A few notes:

一些注意事项:

  • I use a withblock so that the file is safely closed on the completion of this code. You can always call file.closeyourself, but this is better practice.
  • I wrap the access to the 6th column of the line in a try...exceptbecause, well, there might not be a 6th column. Better safe than sorry.
  • 我使用了一个with块,以便在完成此代码时安全地关闭文件。你总是可以给file.close自己打电话,但这是更好的做法。
  • 我将对该行第 6 列的访问包含在 a 中,try...except因为可能没有第 6 列。安全总比后悔好。

回答by Marek Polia?ek

My names.csv file.

我的名字.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

My code in python

我在 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'])