使用 DataFrames 每天将数据记录到 Excel

Recording data on a daily basis onto Excel using DataFrames

早上好,我现在正在做一个 RPi 项目,它每秒捕获一些数据并将其转换为数字。我希望 RPi 将这个 number/time 数据保存到一个 excel 文件,我也希望这个文件可以访问,数据是 "graph-able" 取决于用户输入(即用户想要数据来自过去 3 天的数据 > 过去 3 天的数据输出图)。我知道这可以分为两部分:读取和保存数据(1)以及拉取和绘制数据(2)。对于这个问题,我想关注(1)。

为了从传感器读取数据并将其保存到充当数据库的 excel 文件中,我正在考虑使用 pandas' DataFrame。为什么,你可能会问。我的代码基于前人留下的以前的代码,它已经有类似的 read/write 代码。然而,规模有很大不同(~50 个条目与~38000 个条目)。

我正在考虑将数据记录为:

Basic Text Sample Data in Excel

如您所见,如果每秒都有数据,那么我一天会得到 86400 个条目。

写吧,我保存这个数据的代码如下。我为要保存的数据做了一个class,里面有变量:

class ShiftDataSet:

def __init__(self):
    self.effDataList = []
    self.timeDataList = []
    self.dateTimeToday = datetime.datetime.now()
    self.date = self.dateTimeToday.strftime("%y%b%d")#str
    #%y is year without century, %b is month abbv, %d is day of month

然后(尝试)将此数据记录到数据帧中,然后记录到 excel 文件中,如下所示:

def saveToDf(self):
    dataToSave = {self.date : self.effDataList}
    #dictionary of data to save. effDataList is the list of 1's and 0's as read by the second.

    dfToSave = pd.DataFrame(dataToSave, index=self.timeDataList)
    #create DataFrame to save as Excel, using timeDataList as index. timeDataList is a str list of the second the recording is taken

    print("Attempting to save data")

    #code to combine dfToSave with old df record
    oldDf = pd.read_excel("/home/pi/Sensor/FS Days/Shift Record Template.xlsx")
    #oldDf is the database template, structured the same way like the "Data in Excel" image above

    result = dfToSave.combine_first(oldDf)
    #combine new dataframe of new data with template database

    writer = pd.ExcelWriter("/home/pi/Sensor/FS Days/Shift Record Template.xlsx")
    result.to_excel(writer, 'Sheet 1')

    writer.save()
    print("Save Complete")

    return

我根据我前任的小规模录音代码对这段代码进行了建模。 运行 然而,这段代码,我 运行 进入了数据没有正确写入 excel 文件的问题,结果如下: Messed Data

所以我的问题是:
1) 如何将每秒采集的数据记录到正确的 "seconds" 索引中?
2) 每秒记录和保存数据,还是将其集中到一个更大的列表中,然后在一天中保存一次或两次更好?
3) pandas DataFrame 是我想做的最好的解决方案,还是有更好的方法?

非常感谢您的帮助。

1) 就像您为 dfToSave 定义索引一样,当您 read_excel().

时也必须这样做

2) 我想这主要取决于您的硬件;没有任何背景资料很难做出这样的判断。

3) 我也会使用 pandas 但这并不意味着它是最好的方法。您可以查看其他 excel 库以获取 Python 我猜...