使用python3.x每隔5行检查一次csv

时间:2017-08-10 01:35:00

标签: python python-3.x pandas csv time

csv数据:

>c1,v1,c2,v2,Time

>13.9,412.1,29.7,177.2,14:42:01

>13.9,412.1,29.7,177.2,14:42:02

>13.9,412.1,29.7,177.2,14:42:03

>13.9,412.1,29.7,177.2,14:42:04

>13.9,412.1,29.7,177.2,14:42:05

>0.1,415.1,1.3,-0.9,14:42:06

>0.1,408.5,1.2,-0.9,14:42:07

>13.9,412.1,29.7,177.2,14:42:08

>0.1,413.4,1.3,-0.9,14:42:09

>0.1,413.8,1.3,-0.9,14:42:10

我目前的代码:

import pandas as pd
import csv 
import datetime as dt


#Read .csv file, get timestamp and split it into date and time separately
Data = pd.read_csv('filedata.csv', parse_dates=['Time_Stamp'], infer_datetime_format=True)
Data['Date'] = Data.Time_Stamp.dt.date
Data['Time'] = Data.Time_Stamp.dt.time
#print (Data)
print (Data['Time_Stamp'])
Data['Time_Stamp'] = pd.to_datetime(Data['Time_Stamp'])
#Read timestamp within a certain range
mask = (Data['Time_Stamp'] > '2017-06-12 10:48:00') & (Data['Time_Stamp']<= '2017-06-12 11:48:00')
june13 = Data.loc[mask]
#print (june13)

我要做的是每5秒读取一次数据,如果c1的数据中有1分为10.0及以上,请替换{{1用0.

我还是python的新手,我找不到这方面的例子。我可以提供一些帮助,因为这个问题远远超出了我的python编程技能。谢谢!

1 个答案:

答案 0 :(得分:1)

我不知道csv文件周围的模块所以我的答案可能看起来很原始,我不太确定你在这里想要完成什么,但是你是否以文本方式处理文件?

从我得到的,你想要读取每个c1,检查值并修改它。

要阅读和修改文件,您可以执行以下操作:

with open('filedata.csv', 'r+') as csv_file:
    lines = csv_file.readlines()

    # for each line, isolate data part and check - and modify, the first one if needed.
    # I'm seriously not sure, you might have wanted to read only one out of five lines. 
    # For that, just do a while loop with an index, which increments through lines by 5.
    for line in lines:
        line = line.split(',')  # split comma-separated-values

        # Check condition and apply needed change.
        if float(line[0]) >= 10:
            line[0] = "0"  # Directly as a string. 

        # Transform the list back into a single string.
        ",".join(line)

    # Rewrite the file.
    csv_file.seek(0)
    csv_file.writelines(lines)

    # Here you are ready to use the file just like you were already doing.
    # Of course, the above code could be put in a function for known advantages.

(我这里没有python,所以我无法测试它,并且可能存在拼写错误。)

如果您只需要没有修改文件的数据框:

说实话,几乎一样。 而不是最后的文件写作,你可以这样做:

from io import StringIO  # pandas needs stringIO instead of strings.

# Above code here, but without the last 6 lines.

Data = pd.read_csv(
    StringIo("\n".join(lines)),
    parse_dates=['Time_Stamp'],
    infer_datetime_format=True
)

这应该为您提供您拥有的数据,并在需要时更改值。

希望这不是完全关闭的。此外,有些人可能会发现这种方法很糟糕;我们已经编写了工作模块来做这类事情,那么为什么要自己处理粗糙的原始数据呢?就个人而言,我认为如果我不试图理解如何使用文件的文本表示,那么通常比学习我将要使用的所有外部模块容易得多。您的意见可能不同。

此外,此代码可能会导致性能降低,因为我们需要迭代两次文本(pandas在阅读时会这样做)。但是,我不认为你通过像你已经做的那样读取csv会得到更快的结果,然后反复遍历数据来检查条件。 (你可能会赢得每个c1检查值的转换,但差异很小,并且通过pandas迭代数据帧也可能比列表慢,具体取决于它们当前优化的状态。)

当然,如果你真的不需要pandas数据帧格式,你可以完全手动完成它,它只需要几行(或者不是,tbh)并且不应该慢,如迭代量将最小化:您可以在阅读时同时检查数据条件。现在已经很晚了,我确信你可以自己解决这个问题,所以我不会在我的优秀编辑器中编写代码(称为stackoverflow),询问是否有任何内容!