【问题标题】:search column, return row from excel using python搜索列,使用python从excel返回行
【发布时间】:2014-04-01 02:09:32
【问题描述】:

我有一个包含日期的列 A 的 csv 文件。我想搜索日期并以数组(非常重要)格式返回相应的行。我将如何使用 python 做到这一点?谢谢。

excel文件:

      A          B         C
1  12202014     403       302

2  12212014     312       674

3  12222014     193       310

输入:

 Search csv file for 12212014

输出:

[12212014,312,674]

尝试代码:

date = '12212014'
with open('dates.csv', 'rt') as f:
     reader = csv.reader(f, delimiter=',')
     for row in reader:
          if date == row[0]: 
              print "found the date"

如何返回行而不是仅返回打印语句?

【问题讨论】:

  • @PauloScardine 你好。我尝试查看它,但它没有告诉我如何在特定列中搜索并以数组格式返回整行

标签: python excel csv


【解决方案1】:

基本思路是创建字典/映射date->line,通过key获取值:

import csv


data = {}
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    for line in reader:
        data[line[0]] = line

date_to_find = '12212014'
print data.get(date_to_find, 'Date not found')

打印:

['12212014', '312', '674']

如果您之后需要映射来查找其中的日期,这会有所帮助。

另一种方法是使用生成器表达式遍历文件中的行,直到找到日期:

import csv


date_to_find = '12212014'
with open('test.csv', 'r') as f:
    print next((line for line in csv.reader(f) if line[0] == date_to_find), 
               'Date not found')

打印:

['12212014', '312', '674']

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多