pandas 检查csv文件中的特定列是否包含数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33722389/
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-09-14 00:14:12  来源:igfitidea点击:

Check if specific column in csv file contains data

pythoncsvpandas

提问by PurpleCoffee

I need to check of the third column of my row contains 2016.

我需要检查我行的第三列包含 2016 年。

My code so far:

到目前为止我的代码:

    import csv
    import pandas
    from docutils.utils import column_indices
    from bsddb.dbtables import contains_metastrings
    file = open("Advertising.csv")

    #write new file
    c = csv.writer(open("boop.csv", "wb"))
    #read in original file
    readCSV = csv.reader(file,delimiter= ",")


    for row in readCSV :
        print "something"
        #if contains(2016)
        if readCSV.index_col(2).Contains('2016') :
            print "2016 spotted"
            c.writerow(row)

    file.close()

The line checking the third column is wrong and produces and error: AttributeError: '_csv.reader' object has no attribute 'index_col' Can anyone help with this?

检查第三列的行是错误的,并产生错误:AttributeError: '_csv.reader' object has no attribute 'index_col' 谁能帮忙解决这个问题?

回答by Lo?c G.

You don't need pandasfor this. csvmodule would be fine

你不需要pandas这个。csv模块会很好

import csv

with open("file.csv", "rb") as f:
    csvreader = csv.reader(f, delimiter=",")
    for row in csvreader:
        if "2016" in row[2]:
            print "2016 spotted"