【问题标题】:How to Search a CSV file for a String and get It's Row Index In Python 2.7如何在 CSV 文件中搜索字符串并在 Python 2.7 中获取它的行索引
【发布时间】:2017-04-19 02:32:20
【问题描述】:

我正在尝试打开 csv 并在第一列中搜索电子邮件。如果存在,则检查该特定行的第 3 列是否 = '1'。我不知道如何只检查包含电子邮件的行的第三列。有没有办法可以获取电子邮件所在行的索引?然后我可以执行类似 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

【问题讨论】:

  • row[4] 是当前行的第五列,row[4][2] 是第五列的第三个字符。你不想检查第三列吗? (row[2])
  • @DYZ 是的,谢谢,我编辑了这个问题。我不小心上升了 1 而不是下降。
  • row[3] 仍然不是第三列,而是第四列。此外,您可能不需要[2] 部分,只需检查if row[2]=='1'
  • @DYZ第4行第3列,不知道顺序是行/列还是列/行
  • row 是您的 当前 行。 reader 是已读取的所有行的列表。所以,reader[3][2]=='1'.

标签: python excel python-2.7 csv


【解决方案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'))

【讨论】:

  • 效果很好!我用我现在使用的代码更新了我的问题,你会做任何改变吗?
  • @抱歉,我不太明白你的意思。你希望我改变什么?
  • 对不起,我在更新问题之前发表了评论。我只是不知道是否有更清洁的方式来做我正在做的事情。
  • 哦,对了,既然你已经复制了你的问题的答案,我会保持我的答案不变,因为它更通用。你会接受这个作为你的答案吗?
猜你喜欢
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多