Python 中的 CSV 文件(滑动 Window)

CSV Files in Python (Sliding Window)

我是 Python 的初学者,我需要帮助来处理 Python 中的 csv 文件。 我正在尝试为数据集中的每一行执行滑动 window 机制。

举个例子,如果数据集是这样的

timestamp | temperature | windspeed
965068200   9.61883  60.262   
965069100   9.47203  60.1664 
965070000   9.31125  60.0145   
965070900   9.13649  59.8064

如果用户指定 window 大小为 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

我可以通过使用 Java.Reading CSV 中的 ObjectsArray 列表并生成包含转换数据集的新 CSV 来做到这一点。 这是代码 http://pastebin.com/cQnTBg8d #研究

我需要在Python做这个,请帮我解决这个问题。

谢谢

此答案假定您使用的是 Python 3.x - 对于 Python 2.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)

实际上这段代码都是关于使用队列来保留 window 的输入行,而不是更多 - 其他一切都是文本到列表到文本。

使用实际的 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)