如何在CSV文件中搜索字符串并在Python 2.7中获取它的行索引

时间:2017-04-19 02:32:20

标签: python excel python-2.7 csv

我正在尝试打开csv并在第1列搜索电子邮件。如果存在,则检查该特定行的第3列是否为“1”。我无法弄清楚如何仅检查其中包含电子邮件的行的第3列。有没有办法可以获得电子邮件所在行的索引?那么我可以像row [Row#] [2]那样做,所以它会用电子邮件搜索该行的第3列。这就是我现在所拥有的:

with open('MyFile.csv', 'rb') as f:     
    reader = list(csv.reader(f))
    for row in reader:
        if Email in row[0]:   #checks if email exist
            if '1' in row[2]:   #searches every row instead of just the one with email
                print "Account Already = 1"

如何添加以下内容:

with open('MyFile.csv', 'rb') as f:     
    reader = list(csv.reader(f))
    for row in reader:
        if Email in row[0]:
            print Email.index
            #(lets say it returns '4')
            if '1' in row[3][2]:   #searches only 4th row for '1' 
                quit()

编辑 - 我得到了它,这就是我正在使用的:

df =pd.read_csv('myfile.csv')

a = np.where((df['Email'] == Email) & (df['Num'] == '1'))
try:
    if (a[0][0] + 1) > 0:
    print "Account = 1"
    quit()
except IndexError:
    pass

1 个答案:

答案 0 :(得分:1)

import pandas as pd
import numpy as np

df = pd.read_csv('your_csv.csv')

np.where((df['email_column_name']=='email_to_lookup@email.com') & (df['3rd column name']== '1'))