通过csv从特定行向下搜索 [英] Search through csv from specific row down
问题描述
这是后续追踪:此问题
我使用的代码是:
import csv
file1reader = csv.reader(open("file1.csv"), delimiter=",")
file2reader = csv.reader(open("file2.csv"), delimiter=",")
header1 = file1reader.next() #header
header2 = file2reader.next() #header
for Code, DTime in file1reader:
for id_, D, Sym, DateTime, Bid, Ask in file2reader:
if DateTime.startswith(DTime): # found it
print id_, Code, DateTime, Bid, Ask # output data
break # break and continue where we left next time
结果示例:
1375023013 1 2010-12-26 17:01:01 1.311200 1.311500
1375023592 2 2010-12-26 17:07:16 1.311700 1.312000
1375024176 2 2010-12-26 17:15:04 1.311300 1.311600
对于这些结果的每一行,我想要在file2.csv中搜索id_值,并从该行向下搜索列,为> = Bid + 0.0010 OR< ; = Bid-0.0015。基本上,从那个条目开始,什么价格先来? Bid + 0.0010或Bid-0.0015?我需要使用> =& < =因为价格不连续。一旦找到该条目,我想通过为找到的DateTime和Bid添加一个列来附加原始结果。
With each row of these results, I want to search for the id_ value back in file2.csv, and from that row down, search column Bid for the value that is >= Bid+0.0010 OR <= Bid-0.0015. Basically, from that entry onwards, what price comes first? Bid+0.0010 or Bid-0.0015? I need to use >= & <= since the prices are not continuous. Once that entry is found, I want to append the original result by adding a column for the found DateTime and Bid.
预期结果:
id_ Code DateTime Bid Ask NextDateTime NextBid
1375023013 1 2010-12-26 17:01:01 1.311200 1.311500 2010-12-26 17:03:02 1.312200
1375023592 2 2010-12-26 17:07:16 1.311700 1.312000 2010-12-26 17:09:03 1.311100
1375024176 2 2010-12-26 17:15:04 1.311300 1.311600 2010-12-26 17:20:02 1.312400
再次感谢
推荐答案
要通过csv从特定行向下搜索,请尝试使用 itertools.dropwhile 。
To "search through csv from specific row down", try using itertools.dropwhile.
要通过添加列来追加原始结果,您需要使用新数据重写文件。 fileinput模块 可以轻松做到当 inplace 设置为true时)。
To "append the original result by adding a column", you will need to rewrite the file with the new data. The fileinput module makes that easy to do when inplace is set to true).
这篇关于通过csv从特定行向下搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!