我是Python的初学者,我需要一个在Python中操作csv文件的帮助。我试图为数据集中的每一行执行滑动窗口机制。
的示例,如果数据集为
timestamp | temperature | windspeed
965068200 9.61883 60.262
965069100 9.47203 60.1664
965070000 9.31125 60.0145
965070900 9.13649 59.8064如果用户指定的窗口大小为3,则结果应该如下所示
timestamp | temperature-2 | temperature-1 |temperature-0 | windspeed-2 | windspeed-1 | windspeed-0
965070000 9.61883 9.47203 9.31125 60.262 60.1664 60.0145
965070900 9.47203 9.31125 9.13649 60.1664 60.0145 59.8064我可以使用ObjectsArray在Java.Reading CSV中的列表来实现这一点,并生成包含转换数据集的新CSV。这是代码http://pastebin.com/cQnTBg8d #研究
我需要用Python来做这个,请帮我解决这个问题。
谢谢
发布于 2016-09-08 10:19:38
这个答案假设您使用的是Python3.x-对于Python2.x,需要进行一些更改(一些明显的地方需要注释)
对于问题中的数据格式,这可能是Python中的一个起点:
import collections
def slide(infile,outfile,window_size):
queue=collections.deque(maxlen=window_size)
line=infile.readline()
headers=[s.strip() for s in line.split("|")]
row=[headers[0]]
for h in headers[1:]
for i in reversed(range(window_size)):
row.append("%s-%i"%(h,i))
outfile.write(" | ".join(row))
outfile.write("\n")
for line in infile:
queue.append(line.split())
if len(queue)==window_size:
row=[queue[-1][0]]
for j in range(1,len(headers)):
for old in queue:
row.append(old[j])
outfile.write("\t".join(row))
outfile.write("\n")
ws=3
with open("infile.csv","r") as inf:
with open("outfile.csv","w") as outf:
slide(inf,outf,ws)实际上,这段代码的全部内容是使用队列来保留窗口的输入行,而不是更多--其他的都是从文本到列表到文本。
使用实际csv-数据(请参阅注释)
import csv
import collections
def slide(infile,outfile,window_size):
r=csv.reader(infile)
w=csv.writer(outfile)
queue=collections.deque(maxlen=window_size)
headers=next(r) # r.next() on python 2
l=[headers[0]]
for h in headers[1:]
for i in reversed(range(window_size)):
l.append("%s-%i"%(h,i))
w.writerow(l)
hrange=range(1,len(headers))
for row in r:
queue.append(row)
if len(queue)==window_size:
l=[queue[-1][0]]
for j in hrange:
for old in queue:
l.append(old[j])
w.writerow(l)
ws=3
with open("infile.csv","r") as inf: # rb and no newline param on python 2
with open("outfile.csv","w") as outf: # wb and no newline param on python 2
slide(inf,outf,ws)https://stackoverflow.com/questions/39387857
复制相似问题